Skip to content
jshacks.dev
Fundamentals

JavaScript Interview Question Explain this Keyword

How to answer the this keyword interview question: this is set by how a function is called, and arrows keep the outer one. See the four rules and lost this.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite, npm, Node.js and TypeScript logos.

Of all the questions in a JavaScript interview, this produces the most confident wrong answers. Candidates say that this refers to the object a function belongs to, or to the current scope, and both are close enough to sound right and wrong enough to fail the first snippet. The correct statement is short: the value of this inside a function is decided by how the function is called, not by where it is written, and arrow functions are the exception, since they take this from the place where they were created. This post gives that answer, the four call rules in order of precedence with exact outputs, how arrow functions differ, the follow-up about lost this in callbacks, and the answers that lose the point. The examples run on Node.js 24 as ES modules, where code is strict and top-level this is undefined.

The answer in thirty seconds

this is a hidden parameter that the call supplies. Four rules decide it, and when more than one applies, the first in this list wins. A call with new makes this the new object. A call through call, apply or bind makes this the object you passed. A call written as object.method() makes this the object before the dot. Any other plain call, fn(), gives undefined in strict code and the global object in sloppy code. Arrow functions ignore all four and use the this of the surrounding code.

JavaScript
function describe() {
  return this === undefined ? "undefined" : this.name;
}

const user = { name: "Ada", describe };
const other = { name: "Grace" };

console.log(user.describe());
console.log(describe());
console.log(describe.call(other));
console.log(describe.apply(other, []));

const bound = describe.bind(other);
console.log(bound());
Text
Ada
undefined
Grace
Grace
Grace

The same function gives different answers, because each line calls it differently. The method call used user, the plain call had no object, and call, apply and bind supplied other. An interviewer who sees you write a snippet like this and explain each line has what they asked for.

Rule one: the default call

JavaScript
function whatIsThis() {
  return typeof this;
}

console.log(whatIsThis());
console.log(typeof this);
console.log((function () { return this; })());
Text
undefined
undefined
undefined

In strict mode, a plain call has no this. ES modules and class bodies are always strict, which is why every line prints undefined, including the top level of the module. In a sloppy script the same calls would give the global object, globalThis, and a function that sets this.value would create a global variable by accident. That silent behavior is a reason to write modules.

Rule two: the method call

JavaScript
const counter = {
  count: 0,
  increment() {
    this.count += 1;
    return this.count;
  },
};

console.log(counter.increment(), counter.increment());

const detached = counter.increment;

try {
  detached();
} catch (e) {
  console.log(e.name, "-", e.message);
}
Text
1 2
TypeError - Cannot read properties of undefined (reading 'count')

When counter.increment() is called, the part before the dot becomes this. Copying the method into a variable and calling it removes the object from the call, so this is undefined and reading this.count fails. This is the single most common this bug: a method passed somewhere as a value. A related trick question uses parentheses.

JavaScript
const obj = {
  name: "obj",
  who() {
    return this === undefined ? "undefined" : this.name;
  },
};

console.log(obj.who());
console.log((obj.who)());
console.log((0, obj.who)());
Text
obj
obj
undefined

Wrapping the member access in plain parentheses does not change anything, so this is still obj. The comma operator evaluates to the bare function, and the call that follows has no object, so this is undefined. The thing that matters is whether the call expression is a reference with an object attached.

Rule three: explicit binding

call and apply invoke the function with a chosen this, and bind returns a new function with one fixed.

JavaScript
function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const ada = { name: "Ada" };

console.log(greet.call(ada, "Hello", "!"));
console.log(greet.apply(ada, ["Hi", "?"]));

const hello = greet.bind(ada, "Hello");
console.log(hello("."));

const rebound = hello.bind({ name: "Someone else" });
console.log(rebound("..."));
console.log(hello.call({ name: "Another" }, "!"));
Text
Hello, Ada!
Hi, Ada?
Hello, Ada.
Hello, Ada...
Hello, Ada!

call takes the arguments one by one and apply takes them as an array. A bound function keeps its this for good: binding it again, or calling it with call, does not change it. The last two lines show a bound function ignoring a new this. bind can also fix leading arguments, as hello does with the greeting, which is called partial application.

Rule four: new

JavaScript
function Person(name) {
  this.name = name;
}

const person = new Person("Ada");
console.log(person.name, person instanceof Person);

try {
  Person("Grace");
} catch (e) {
  console.log(e.name, "-", e.message);
}

function Fixed() {
  this.value = "from new";
}

const Bound = Fixed.bind({ value: "from bind" });
console.log(new Bound().value);
Text
Ada true
TypeError - Cannot set properties of undefined (setting 'name')
from new

A call with new creates a fresh object and makes it this. Leaving out new in strict code is a TypeError, and in sloppy code it would have set a global. The last example shows the precedence: new beats bind, so the bound object is ignored and value comes from the constructor. A class is the modern form of the same rule, and it throws if you call it without new.

Arrow functions

An arrow function has no this of its own. It looks up the one from the scope where it was written, like any other variable.

JavaScript
const timer = {
  seconds: 0,
  start() {
    const regular = function () {
      return this === undefined ? "undefined" : "defined";
    };
    const arrow = () => this.seconds;

    this.seconds = 5;
    return [regular(), arrow()];
  },
};

console.log(timer.start());

const objectWithArrow = {
  name: "obj",
  read: () => typeof this,
};

console.log(objectWithArrow.read());
console.log(objectWithArrow.read.call({ name: "other" }));
Text
[ 'undefined', 5 ]
undefined
undefined

Inside start(), the regular nested function is a plain call and has no this, and the arrow function takes this from start, which is timer. That is the use case for arrows: callbacks that need the outer this. The second half shows the opposite mistake: an arrow used as an object method takes this from the module, where it is undefined, and call cannot change it. Do not write methods as arrow functions on object literals.

Follow-up: why does this get lost in callbacks?

JavaScript
class Counter {
  count = 0;

  increment() {
    this.count += 1;
    return this.count;
  }

  incrementArrow = () => {
    this.count += 1;
    return this.count;
  };
}

const counter = new Counter();

try {
  [1, 2].forEach(counter.increment);
} catch (e) {
  console.log(e.name);
}

console.log([1, 2].map(counter.incrementArrow));
console.log([1, 2].map(counter.increment.bind(counter)));
console.log([1].map(function () { return this.count; }, counter));
Text
TypeError
[ 1, 2 ]
[ 3, 4 ]
[ 4 ]

Passing counter.increment hands the array method a bare function, which it calls with no object, so this is undefined and the TypeError follows. The arrow class field closes over the instance, which solves it at the price of one function per instance. bind fixes this at the call site, and map and forEach accept a second argument that is used as this for a regular function callback. All three are valid answers to the follow-up, and the interviewer wants to hear that you know the cause before the cures.

Wrong answers that lose the point

  • "this is the object that owns the function." A function is not owned: the same function can be called through several objects, or none.

  • "this is the current scope." Scope is about variable lookup, and this is not a variable, except in arrow functions, where it is looked up like one.

  • "Arrow functions are just shorter functions." They differ in this, arguments, new and prototype.

  • "bind changes the original function." It returns a new one and leaves the original alone.

A mistake we hit: a method passed as an event handler

JavaScript
class Toggle {
  constructor() {
    this.on = false;
  }

  flip() {
    this.on = !this.on;
    return this.on;
  }
}

function addListener(handler) {
  return handler();
}

const toggle = new Toggle();

try {
  addListener(toggle.flip);
} catch (e) {
  console.log(e.name);
}

console.log(addListener(() => toggle.flip()));
console.log(addListener(toggle.flip.bind(toggle)));
Text
TypeError
true
false

The handler was registered by passing the method itself, and the registering code called it as a plain function. The class body is strict, so this was undefined and the first call failed. Wrapping the call in an arrow function, or binding, fixed it, and the state flipped on the two later calls. In the browser, the DOM sets this to the element for a regular function handler, which hides this bug on some code paths and surfaces it on others. We now use an arrow function at the registration site, so that the owner of the method is visible there.

Choosing between the fixes

You haveUse
A method passed as a callbackbind, an arrow wrapper, or an arrow class field
A callback inside a method that needs the outer thisAn arrow function
A one-off call with a chosen thiscall or apply
A function that is always called on one objectbind once
An object methodA method shorthand, never an arrow
A constructorA class, called with new

Practical rules we follow

Write ES modules and classes, so a lost this is an error and not a global write. Use method shorthand on object literals and arrows for callbacks inside methods. Bind or wrap at the point where a method is passed on. Prefer plain functions with parameters over code that depends on this, since they are easier to test. And when you debug, look at the call site, not the definition.

Where the this answer stops being enough

A deeper question covers this in event handlers, in getters and setters, in Reflect.apply, in super calls and in with blocks. It also covers the difference between sloppy and strict boxing: in sloppy mode, a primitive passed as this is wrapped in an object. The four rules and arrows answer most of what is asked. The reference is in the [MDN this page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) and the ECMAScript specification.

Taggedinterview
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.