Interview FAQ javascript FAQ

OOPS in JavaScript interview questions with answers for developers

This article provide interview questions for javascript. This will cover OOPS concept inheritance, overriding, prototype, polymorphism etc.

What is object literal?

Object literal is a comma-separated list of name-value pairs wrapped in curly brace.

var fullName = {
      firstName : "Stephene", // name : value
      lastName : "Meyer"
}
What is factory function?

Factory function returns object without using new keyword.

 function sayHello(name) {
   return {
     name : name, // it means name:name
     hello() {
       console.log("Hello",name);
     }
   };
 }
 const  sayhello  =  sayHello("World"); // created object sayhello 
 console.log(sayhello);
 console.log(sayhello.name);
 console.log(sayhello.hello()); 
What is constructor function?

In constructor function object is created using new keyword. The properties of function initialized using this keyword.

 function sayHello(name) {
     this.name = name, // it means radius:radius
     this.hello = function(name) {
       console.log("Hello",this.name);
     }
  }
 const  sayhello  = new sayHello("World");//creating object sayhello
 console.log(sayhello);
 console.log(sayhello.name);
 console.log(sayhello.hello());  
What does new operator do in JavaScript?

“new” keyword in JavaScript creates a blank object and link this object to another object and passes the newly created object as this context. It returns this if the function doesn’t return its own object.

function sayHello(name) {
     this.name = name, // it means radius:radius
     this.hello = function(name) {
       console.log("Hello",this.name);
     }
  }
 const  sayhello  = new sayHello("World");
 console.log(sayhello.name);
 console.log(sayhello.hello()); 

By default this refers to window object.

What is the difference between factory and constructor function?

In Constructor function object is created using new keyword while factory function simply returns an object without using new keyword.

What is constructor property?

It returns the reference Object constructor function that created the instance object.

const obj = {};
console.log(obj.constructor);
How functions are objects in JavaScript?

Functions are object because function can be assign to a variable, array or other objects. Also they can be passed as argument to other functions.

Example : Function assigned to a variable.

const o = function abc() { console.log("Hello World!!");} 
console.log(o()); // returns Hello World!!

Example : Function Passed as arguments

 function xyz(a) { 
       console.log(a); 
 } 
 function abc(a, func) { 
    func(a); 
 } 
 abc(3, xyz);  // xyz passed as arguments 
What does .call() method do?

The call() method calls a function with a given this value and arguments provided individually

function Product(name, price) {
   this.name = name;
   this.price = price;
 }
 function Food(name, price) {
   Product.call(this, name, price);
   this.category = 'food';
 }
 console.log(new Food('cheese', 5).name);
 // expected output: "cheese"
What is primitive(value type) and reference type ?

Primitive Type: boolean, undefined, null, string, number called as primitive data type as data is passed by value.

var x = 10; 
var a = 5; 
x = a; 
a = 20;
console.log(x) // x value is 5
console.log(a) // a value is 20 

Reference Type : object, array, function are called as reference type. In this variable don’t actually contain the value.

var x = {name: 'Rahul'}; 
var y = x;
y.name = "Ram";
console.log(x) // x value is Ram
console.log(y) // a value is Ram 
What is abstraction in JavaScript?

Abstraction means hiding the details and show only essentials.
Object can not be created for an abstract class.

 //Creating a constructor function  
function Vehicle()  
{  
    this.vehicleName="vehicleName";  
    throw new Error("You cannot create an instance of Abstract Class");  
}  
Vehicle.prototype.display=function()  
{  
    return "Vehicle is: "+this.vehicleName;  
}  
//Creating a constructor function  
function Bike(vehicleName)  
{  
    this.vehicleName=vehicleName;  
}  
//Creating object without using the function constructor  
Bike.prototype=Object.create(Vehicle.prototype);  
var bike=new Bike("Honda");  
document.writeln(bike.display());   
What is getter and setter in JavaScript?

Getter : used to get the value

 // Create an object:
 var person = {
  firstName: "John",
     lastName : "Doe",
     language : "en",
     get lang() {
     return this.language;
     }
};

 // Display data from the object using a getter:
 console.log(person.lang);

Setter : used to set the value

 var person = {
   firstName: "John",
   lastName : "Doe",
   language : "",
     set lang(lang) {
     this.language = lang;
     }
};

 // Set an object  property using a setter:
 person.lang = "en";

 // Display data from the object:
console.log(person.language)
What is inheritance in JavaScript? What do you mean by Prototypes and Prototypical Inheritance ?

Inheritance means acquiring the properties of some another class or object. In JavaScript inheritance works through something called prototypes and this form of inheritance is often called prototypical inheritance.

 function Brick() {   
      this.width = 10;   
      this.height = 20; 
 } 
 function BlueGlassBrick() {   
      Brick.call(this);   
      this.opacity = 0.5;   
      this.color = 'blue'; 
 } 

For better understanding go through this article.

What is multilevel inheritance in JavaScript?
 var Model = function () {
     this.names = ["name1", "name2"];
 };
 var Item = function () {
     //When inheriting in Javascript you must 
     //call the inherited function's constructor manually.
     Model.call(this);
 };
 //Inherit Model's prototype so you get all of Model's methods.
 Item.prototype = Object.create(Model.prototype);
 Item.prototype.constructor = Item;
 Item.prototype.init = function (item_name) {
     this.names[0] = item_name;
 };
 var Employee = function () {
     Model.call(this);
 };
 Employee.prototype = Object.create(Model.prototype);
 Employee.prototype.constructor = Employee;
 var myItem = new Item();
 myItem.init("New Name");
 //prints New Name, name2
 console.log(myItem.names);
 var myEmployee = new Employee();
 //prints name1, name2
 console.log(myEmployee.names);
What is property descriptor?

Each property is having property descriptor that helps to see all the attributes of that property.

 var bike = {
  name: 'SuperSport', 
  maker: 'Ducati'
};
console.log(Object.getOwnPropertyDescriptor(bike, 'maker')); 
What is Object.define Property ?

The static method Object.defineProperty() defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

const object1 = {};
Object.defineProperty(object1, 'property1', {
   value: 52,
});
console.log(object1.property1);
What is .prototype?

JavaScript is often described as a prototype-based language — to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from.

An object’s prototype object may also have a prototype object, which it inherits methods and properties from, and so on. This is often referred to as a prototype chain, and explains why different objects have properties and methods defined on other objects available to them.

Well, to be exact, the properties and methods are defined on the prototype property on the Objects’ constructor functions, not the object instances themselves.

prototype property also allows you to add new methods to objects constructors:

 function Person(first, last, age, eyecolor) {
     this.firstName = first;
     this.lastName = last;
     this.age = age;
     this.eyeColor = eyecolor;
 }

 Person.prototype.name = function() {
     return this.firstName + " " + this.lastName;
 }; 
What is super constructor?

The super keyword is used to access and call functions on an object’s parent.

class Rectangle {
   constructor(height, width) {
     this.name = 'Rectangle';
     this.height = height;
     this.width = width;
   }
   sayName() {
     console.log('Hi, I am a ', this.name + '.');
   }
   get area() {
     return this.height * this.width;
   }
   set area(value) {
     this._area = value;
   }
 }
 class Square extends Rectangle {
   constructor(length) {
     this.height; // ReferenceError, super needs to be called first!
 // Here, it calls the parent class's constructor with lengths // provided for the Rectangle's width and height super(length, length); // Note: In derived classes, super() must be called before you // can use 'this'. Leaving this out will cause a reference error. this.name = 'Square';
 }
 }
 
What is method overriding?

When multiple functions are defined which have the same name, the last one will override all the previously defined functions and every time when function is invoked, the last defined one will get executed.

User defined function override

function addNum(x, y, z) {  
        return x + y + z;  
}  
function addNum(x, y) {  
        return x + y;  
}  
var result = addNum(1, 2, 3);  
console.log(result); // print 3 instead of 6. last parameters will be ignored.

over-riding built in function

var alert = function(message) {  
       console.log(message);  
}  
alert("Learn");  // overiding alert method
alert("JavaScript");   
What is object.assign?

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
What is mixin?

JavaScript doesn’t support multiple inheritance. But sometimes there is a need to add functionality of 2 classes to a single object. Mixin is a way properties are added to objects without using inheritance

For example, let’s say we have a Person class. And we want people to be able to say Hi. We can create a sayHiMixin and use it to make People say hi

let sayHiMixin = {
    sayHi() {
       console.log(Hello ${this.name});
    },
    sayBye() {
       console.log(Bye ${this.name});
    }
 };
 class Person {
    constructor(name) {
       this.name = name;
    }
 }
 // copy the methods
 Object.assign(Person.prototype, sayHiMixin);
 new Person("John").sayHi();

For further reading checkout JavaScript question answers with ES6 and for beginners.

Reference :
https://www.tutorialspoint.com/mixins-in-javascript

Leave a comment