Interview Q&A / JavaScript
JavaScript interview questions
Closures, the event loop, this, promises and the core language questions every frontend round asks.
Prefer rapid revision? Practise JavaScript short interview answers →
- 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 - What is the difference between call, apply and bind?
All three set this for a function. call runs it now with arguments listed one by one, apply runs it now with an array of arguments, and bind returns a new function with this fixed, to be run later.
BeginnerQuick answer1 min read - 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 - 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 - 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 - 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 - 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 - What is this after calling bind twice on the same function?
The first bind wins. A bound function's this is permanent, so calling bind again on it, or call and apply, cannot change it. Only extra preset arguments from the second bind take effect.
AdvancedQuick answer1 min read