TechnicalMedium JavaScript

How does the this keyword work in JavaScript?

Asked for Frontend Developer, Full-Stack Developer

Why they ask this: Bugs with lost this in callbacks are common, and the answer shows depth beyond syntax.

Answer

this depends on how a function is called, not where it is written:

Call stylethis
obj.method()obj
plain fn()undefined in strict mode (the global object otherwise)
new Fn()the new object
fn.call(x) / fn.apply(x) / fn.bind(x)x
arrow functionthis of the surrounding scope (arrows have no own this)
js
const user = {
  name: 'Hari',
  hello() { return this.name; },
  later() { setTimeout(() => console.log(this.name)); }, // arrow keeps `this`
};

const fn = user.hello;
fn(); // `this` is lost: undefined in strict mode

Fix lost this with an arrow function or .bind(obj).

Can you explain this in your own words?

Back to question bank