JavaScript Interview Questions

What are the possible ways to create objects in JavaScript

There are many ways to create objects in javascript as mentioned below:

  1. Object literal syntax:

    The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.

    var object = {
         name: "Amit",
         age: 40
    };

    Object literal property values can be of any data type, including array, function, and nested object.

    Note: This is one of the easiest ways to create an object.

  2. Object constructor:

    The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.

    var object = new Object();

    The Object() is a built-in constructor function so "new" keyword is not required. The above code snippet can be re-written as:

    var object = Object();
  3. Object's create method:

    The create method of Object is used to create a new object by passing the specificied prototype object and properties as arguments, i.e., this pattern is helpful to create new objects based on existing objects. The second argument is optional and it is used to create properties on a newly created object.

    The following code creates a new empty object whose prototype is null.

    var object = Object.create(null);

    The following example creates an object along with additional new properties.

    let vehicle = {
      wheels: '4',
      fuelType: 'CNG',
      color: 'Green'
    }
    let carProps = {
      type: {
        value: 'Volkswagen'
      },
      model: {
        value: 'Golf'
      }
    }
    
    var car = Object.create(vehicle, carProps);
    console.log(car);
  4. Function constructor:

    In this approach, create any function and apply the new operator to create object instances.

    function Person(name) {
      this.name = name;
      this.age = 21;
    }
    var object = new Person("Amit");
  5. Function constructor with prototype:

    This is similar to function constructor but it uses prototype for their properties and methods,

    function Person() {}
    Person.prototype.name = "Amit";
    var object = new Person();

    This is equivalent to creating an instance with Object.create method with a function prototype and then calling that function with an instance and parameters as arguments.

    function func() {}
    
    new func(x, y, z);

    (OR)

    // Create a new instance using function prototype.
    var newInstance = Object.create(func.prototype)
    
    // Call the function
    var result = func.call(newInstance, x, y, z),
    
    // If the result is a non-null object then use it otherwise just use the new instance.
    console.log(result && typeof result === 'object' ? result : newInstance);
  6. Object's assign method:

    The Object.assign method is used to copy all the properties from one or more source objects and stores them into a target object.

    The following code creates a new staff object by copying properties of his working company and the car he owns.

    const orgObject = { company: 'ABC Corp'};
    const carObject = { name: 'Toyota'};
    const staff = Object.assign({}, orgObject, carObject);
  7. ES6 Class syntax:

    ES6 introduces class feature to create objects.

    class Person {
      constructor(name) {
        this.name = name;
      }
    }
    
    var object = new Person("Amit");
  8. Singleton pattern:

    A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance. This way one can ensure that they don't accidentally create multiple instances.

    var object = new (function () {
      this.name = "Amit";
    })();

What is the difference between Call, Apply and Bind

The difference between Call, Apply and Bind can be explained with below examples,

Call: The call() method invokes a function with a given this value and arguments provided one by one

var employee1 = { firstName: "Rohit", lastName: "Shetty" };
var employee2 = { firstName: "Ved", lastName: "Pandey" };

function invite(greeting1, greeting2) {
  console.log(
    greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2
  );
}

invite.call(employee1, "Hello", "How are you?"); // Hello Rohit Shetty, How are you?
invite.call(employee2, "Hello", "How are you?"); // Hello Ved Pandey, How are you?

Apply: Invokes the function with a given this value and allows you to pass in arguments as an array

var employee1 = { firstName: "Rohit", lastName: "Shetty" };
var employee2 = { firstName: "Ved", lastName: "Pandey" };
function invite(greeting1, greeting2) { console.log( greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2 ); } invite.apply(employee1, ["Hello", "How are you?"]); // Hello Rohit Shetty, How are you? invite.apply(employee2, ["Hello", "How are you?"]); // Hello Ved Pandey, How are you?

Bind: returns a new function, allowing you to pass any number of arguments

var employee1 = { firstName: "Rohit", lastName: "Shetty" };
var employee2 = { firstName: "Ved", lastName: "Pandey" };
function invite(greeting1, greeting2) { console.log( greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2 ); } var inviteEmployee1 = invite.bind(employee1); var inviteEmployee2 = invite.bind(employee2); inviteEmployee1("Hello", "How are you?"); // Hello Rohit Shetty, How are you? inviteEmployee2("Hello", "How are you?"); // Hello Ved Pandey, How are you?

Call and Apply are pretty much interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma separated list of arguments. You can remember by treating Call is for comma (separated list) and Apply is for Array.

Bind creates a new function that will have this set to the first parameter passed to bind().


What is memoization

Memoization is a functional programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache. Let's take an example of adding function with memoization,


const memoizAddition = () => {

  let cache = {};

  return (value) => {

    if (value in cache) {

      console.log("Fetching from cache");

      return cache[value]; //// Here, cache.value cannot be used as property name starts 

      // with the number which is not a valid JavaScript  identifier. 

    // Hence, can only be accessed using the square bracket notation.

} else {

console.log("Calculating result");

      let result = value + 20;

      cache[value] = result;

      return result;

    }

  };

};

// returned function from memoizAddition

const addition = memoizAddition();

console.log(addition(20)); //output: 40 calculated

console.log(addition(20)); //output: 40 cached


Hoisting is a JavaScript mechanism where variables, function declarations and classes are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialisation. Let's take a simple example of variable hoisting,

console.log(message); //output : undefined
var message = "The variable Has been hoisted";

The above code looks like as below to the interpreter,

var message;
console.log(message);
message = "The variable Has been hoisted";

In the same fashion, function declarations are hoisted too

message("Good morning"); //Good morning

function message(name) {
  console.log(name);
}

This hoisting makes functions to be safely used in code before they are declared.


In ES6, Javascript classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance. For example, the prototype based inheritance written in function expression as below,

function Bike(model, color) {
  this.model = model;
  this.color = color;
}

Bike.prototype.getDetails = function () {
  return this.model + " bike has" + this.color + " color";
};

Whereas ES6 classes can be defined as an alternative

class Bike {
  constructor(color, model) {
    this.color = color;
    this.model = model;
  }

  getDetails() {
    return this.model + " bike has" + this.color + " color";
  }
}




What are closures

A closure is the combination of a function bundled(enclosed) together with its lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables, functions and other data even after the outer function has finished its execution. The closure has three scope chains.

  1. Own scope where variables defined between its curly brackets
  2. Outer function's variables
  3. Global variables

Let's take an example of closure concept,

function Welcome(name) {
  var greetingInfo = function (message) {
    console.log(message + " " + name);
  };
  return greetingInfo;
}
var myFunction = Welcome("John");
myFunction("Welcome "); //Output: Welcome John
myFunction("Hello Mr."); //output: Hello Mr. John

As per the above code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.

Comments

Popular posts from this blog

What You Can Do With LINQ to SQL

WCF Overview