Top Javascript Interview Questions Top Javascript Interview Questions

Page content

These JavaScript interview questions are based on my personal interview experience and feedback from other interviewees. These questions verifies your theoretical as well as practical knowledge about JavaScript. Keep following this post for regular updates.

Q1. What is Closure in JavaScript?

  • Definition: A closure is an inner function having access to its outer function scope and all above scopes even when that function is executing outside of its outer function.

  • When you define an inner function inside outer function, a closure is created at runtime for inner function bundled with outer function’s scope. Let’s look at the example to understand Closures

    var outerFunc  = function(c){ 
      var a = 1;
      var innerFunc = function(d) {
        var b = 2;
        var innerMostFunc = function(e) {
          return a + b + c + d + e;
        }
        return innerMostFunc;
      }
      return innerFunc;
    }
    console.dir(outerFunc(3));        //1. innerFunc
    console.dir(outerFunc(3)(4));     //2. innerMostFunc
    console.log(outerFunc(3)(4)(5));  //3. 15
    
    Output
    ▼ ƒ innerFunc(c) length: 1 name: "innerFunc" arguments: null caller: null ➤ prototype: {constructor: ƒ} ➤ __proto__: ƒ () [[FunctionLocation]]: ▼ [[Scopes]]: Scopes[2] ➤ 0: Closure (outerFunc) {c: 3, a: 1} ➤ 1: Global {parent: Window, opener: null, top: Window, length: 1, frames: Window, …} ▼ ƒ innerMostFunc(c) length: 1 name: "innerMostFunc" arguments: null caller: null ➤ prototype: {constructor: ƒ} ➤ __proto__: ƒ () [[FunctionLocation]]: ▼ [[Scopes]]: Scopes[3] ➤ 0: Closure (innerFunc) {d: 4, b: 2} ➤ 1: Closure (outerFunc) {c: 3, a: 1} ➤ 2: Global {parent: Window, opener: null, top: Window, length: 1, frames: Window, …} 15

    We have three console dir/log. Let’s discuss them one by one:

    1. innerFunc has a closure of variables defined or passed as argument in outerFunc

       0: Closure (outerFunc) {c: 3, a: 1}
      
    2. innerMostFunc has a closure of variables defined or passed as argument in in outerFunc and innerFunc i.e.

       0: Closure (innerFunc) {d: 4, b: 2}
       1: Closure (outerFunc) {c: 3, a: 1}
      
    3. innerMostFunc returns a+b+c+d+e=15 where

      • value of a and c is coming from Closure (outerFunc)
      • value of b and d is coming from Closure (innerFunc)
      • value of e is coming from passed argument

Q2. What are Promises and why do we use it?

  • Promises are introduced natively in ES6. They are very similar to our promises. As we keep or break the promise, Javascript promises are either resolve or reject.

  • In earlier days, you would have used callbacks to handle asynchronous operations. However, callbacks have limited functionality and often leads to unmanageable code if you are handling multiple async calls also known as callback hell. Promises were introduced to improve code readability and better handling of async calls and errors.

  • Syntax of simple promise object.

    let promise = new Promise(function (resolve, reject) {
      // asynchronous call
    });
    

Also read this post for more details on promises in javascript

Q3. How to use async and await and what problem does it solve?

  • Async/Await introduced in ECMAScript2017 is a new way to handle asynchronous operation. Its underlying is Promise with improved syntax to write concise, readable and easy to debug code as compare to promises and callbacks.

  • When Async keyword is applied before a function, it turns into asynchronous function and always return a promise object.

  • await keyword works only inside async function and it makes the function execution wait until the returned promise settles (either resolve or reject).

  • Usage of async/await:

     1async function hello() {
     2  let promise = new Promise((resolve, reject) => {
     3    setTimeout(() => resolve("Hello"), 5000)
     4  });
     5
     6  let value = await promise; // wait until the promise resolves
     7
     8  return value;
     9}
    10
    11hello().then(data => console.log(data));
    

    Please note that in above code snippet when we execute async function hello(), function execution literally waits for 5s at line 6 before returning resolved promise object. CPU resources are not utilized in this wait period and can be used for other work.

Also read this post for more details on async/await in javascript

Q4. What is a difference between call, apply and bind in JavaScript?

  • All three call, apply and bind are prototype methods of Function that means you can execute these three methods on any function.
  • All three call, apply and bind methods are used to execute the function in explicit context where this refers to the first argument passed in method.
  • call() - accepts the function arguments as comma separated values arg1, arg2, …
    functionName.call(thisArg, arg1, arg2, ...) 
    
  • apply() - accepts the function arguments as array of values [arg1, arg2, …]
    functionName.apply(thisArg, [arg1, arg2, ...])
    
  • bind() - returns a new bounded function which can be executed later.
    functionName.bind(thisArg)
    
  • call() and apply() methods are executed immediately whereas bind() method return a new bounded function which can be executed later.

Also read this post for more details on difference between call, bind and apply with their practical usage

Q5. What is Arrow function and how it is different from normal functions?

  • Arrow functions are introduced in ES6 and allow us to write shorter function syntax.
    var helloES5 = function() {
        return "Hello World";
    }
    
    var helloES6 = () => "Hello World";
    
  • In normal function this keyword represents the object that called the function but in arrow function this keyword always represents the object that defined the arrow function.

Q6. What is a difference between == and === operator?

  1. == is abstract comparison operator which only compares the content and not its type
       1 == 1            // true, content and its type is same
     '1' == 1            // true, auto type conversion, string converted into number
    null == undefined    // true, because null is equivalent of undefined
       0 == false        // true, because false is equivalent of 0
      "" == false        // true, because false is equivalent of empty string
    
  2. === is strict comparison operator which compare both content and its type
       1 === 1             true
     '1' === 1             false
    null === undefined     false
       0 === false         false
      "" === false         false
    
  3. === is faster then == because == converts the operands to the compatible type before comparison whereas === compares directly without any conversion.

Also read this post for more details on == and === operators with many examples

Q7. What is a difference between undefined and null ?

  • undefined means a variable has been declared but not assigned a value yet.
  • null is an assignment value. It can be assigned to a variable that represents null, empty or non-existent value.
  • undefined is type of undefined whereas null is an object.
    var a;
    console.log(typeof(a));     // undefined
    console.log(typeof(null));  // object
    

Q8. What is a difference between var, let and const keywords?

  • var declarations are globally scoped or function scoped while let and const are block scoped.
  • var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.
  • They are all hoisted to the top of their scope but while var variables are initialized with undefined, let and const variables are not initialized.
  • While var and let can be declared without being initialized, const must be initialized during declaration.

Also read this post for more details on difference between var, let and const

Q9. What is variable Hoisting in JavaScript?

  • Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

  • Variables defined using var, let or const are all hoisted.

  • In hoisting process, var variable is initialized with undefined by default. If you try to access it before declaration then you will get undefined.

  • In hoisting process, let and const variables are not initialized. If you try to access them before declaration then you will get ReferenceError.

    console.log(x);  // undefined
    console.log(y);  // ReferenceError
    console.log(z);  // ReferenceError
    
    var x = 1;
    let y = 2;
    const z = 3;
    

Q10. What are the Object methods available in Javascript?

  • Object.create() method is used to create a new object with its prototype set to existing object.
  • Object.assign() method is used to copy the properties and functions of one object in another object.
  • Object.freeze() freezes the state of an Object once this method is called. It ignores if any existing property is modified, and if any new property is added.
  • Object.seal() seals the state of an Object once this method is called. It allows the modification of existing properties, but ignores if any new property is added.
  • Object.defineProperty() is used to define new property in existing object or modifying existing property. Property can be marked writable, configurable and enumerable.
  • Object.is() is used to compare two values. Return true or false.

Also read this post for more details on Object methods with examples

Q11. What is this keyword in Javascript?

In JavaScript, this keyword refers to the object it belongs to. It has different values depending on where it is used:

  • In a method, this refers to the owner object where method is defined.
  • Alone, this refers to the global object.
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined.
  • When a function called with new keyword, this refers to new object instance.
  • In a DOM event, this refers to the element that received the event.
  • Function prototype methods call(), apply() and bind() can be used to refer this to any object.

Also read this post to understand all about this keyword with examples

Q12. What is the difference between throttle and debounce?

Debounce and throttle are two similar (but different!) techniques to control how many times we allow a function to be executed over time.

  • Throttle If throttle interval is 100ms then a throttled function will be executed only once in 100ms, no matter how often you invoke that function.

    If is useful for rate-limiting events that occur faster than you can keep up with. For e.g. update position at every 1s time interval in infinite scrolling.

    var throttled = _.throttle(updatePosition, 100);
    $(window).scroll(throttled);
    
  • Debounce If debounce interval is 100ms then a debounced function will be executed after 100ms passed since its last execution.

    It is mainly used to group a sudden burst of behavior and react afterwards. For e.g., recalculating a layout 1s after the window has stopped being resized, send event 2s after keystrokes has stopped on an input field, and so on.

    var lazyLayout = _.debounce(calculateLayout, 300);
    $(window).resize(lazyLayout);
    

Underscore and Lodash libraries have built in function for both.

Q13. What is constructor and prototype? Do you know about prototypal inheritance.

We can define classes in JavaScript using function constructor.

// ES5 Function Constructor
var Person = function(firstName, lastName){
  this.firstName = firstName;
  this.lastName = lastName;
}

We can add methods to our class using prototype.

Person.prototype = {
    getFullName(){
        return `${this.firstName.toUpperCase()} ${this.lastName.toUpperCase()}`;
    }
}

We can create a subclass Student of Person class using prototypal inheritance.

var Student = function(firstName, lastName, studentId){
  Person.call(this, firstName, lastName);
  this.studentId = studentId;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

We can further add methods in our subclass using prototype

Student.prototype.toString = function(){
    return `Student {${this.lastName} ${this.firstName} - ${this.studentId}}`
}

Let’s create an object from Student subclass

var student = new Student("Ashish", "Lahoti", 123456);

console.log(student.getFullName());
// prints 'ASHISH LAHOTI'

console.log(student.toString());
// prints 'Student {Lahoti Ashish - 123456}'

Q14. How do you define Class in ES6?

We define class using class keyword in ES6 which is a replacement of function constructor.

// ES6 Class
class Car {
  constructor(brand, color, price) {
    this._brand = brand;
    this._color = color;
    this._price = price;
  }

  // getter method
  get color(){
    return `color is ${this._color.toUpperCase()}`;
  }

  // setter method
  set color(newColor){
    this._color = newColor;
  }

  // prototype method
  drive(){
    return `driving ${this._brand} ${this._color} color car`;
  }

  // static method
  static compareCars(car1, car2){
    return `${car2._brand} is ${(car1._price > car2._price) ? "cheaper" : "costlier"} then ${car1._brand}`
  }
}

We can define getter, setter, prototype and static methods in classes. We can also create subclasses using extend keyword.

class Toyota extends Car {
    constructor(color, price, model, make){
        super("Toyota", color, price);
        Object.assign(this, {model, make});
    }
}

Also read this post for more details on classes in JavaScript

Q15. What is global, function and block scope in Javascript?

Q16. Currying functions in javascript?