Interview Q&A / JavaScript

INTERVIEW Q&A · 71 QUESTIONS

JavaScript interview questions

Closures, the event loop, this, promises and the core language questions every frontend round asks.

  1. How does the this keyword work in JavaScript?

    this is decided by how a function is called, not where it is written. A method call obj.fn() sets this to obj; new sets it to the new object; call, apply and bind set it explicitly; a plain call gives undefined in strict mode. Arrow functions have no own this and use the surrounding one.

    IntermediateIn-depth3 min read
  2. How does this behave inside an arrow function?

    An arrow function has no this of its own. It uses the this of the surrounding code where it was written, and call, apply and bind cannot change it.

    IntermediateQuick answer1 min read
  3. What is method borrowing, and how do call and apply let you do it?

    Method borrowing means using a method from one object on another by passing the other as this with call or apply. A classic case is Array.prototype.slice.call(arguments) on an array-like object.

    IntermediateQuick answer1 min read
  4. What is this inside a plain function call in strict mode versus sloppy mode?

    In sloppy mode a plain call gets the global object as this. In strict mode it gets undefined. Strict mode also stops call from boxing a primitive this into an object.

    IntermediateQuick answer1 min read
  5. Why does a method lose its this when you pass it as a callback, and how do you fix it?

    this is decided by how a function is called, not where it is defined. A detached method is called plainly, with no object before the dot, so this is lost. Fix it with bind, an arrow wrapper or an arrow class field.

    IntermediateQuick answer1 min read
  6. Write your own version of Function.prototype.bind.

    Add a method on Function.prototype that remembers the original function, the chosen this and any preset arguments, and returns a new function that calls the original with apply, joining preset and new arguments.

    IntermediateQuick answerCoding1 min read