Skip to the solution
MediumFrontend7 min read

Explain 'this' keyword in JavaScript.

1.1k views

The problem

Question presented to candidate: "In your own words, what is this in JavaScript, and why do people find it confusing compared to other languages?"

What a strong answer should cover:

  • this is not decided by where a function is defined -- it is decided by how the function is called (the call-site), which makes it fundamentally different from ordinary JavaScript variable lookups.
  • Ordinary variables in JavaScript use lexical scoping: you can tell what a variable refers to just by reading where the code is written. this breaks that pattern -- the exact same function body can produce a different this every single time it is called, depending on the call-site.
  • Arrow functions are the deliberate exception: they do not have their own this at all, and instead capture this lexically from the enclosing scope, which re-aligns this with the rest of the language's normal scoping rules.
  • A single shared function reference, called through different objects (or with none at all), genuinely produces a different this each time -- this is not a special case, it is the general rule.
  • The confusion with other languages usually comes from assuming this behaves like Python's explicit self parameter or Java's this, both of which are fixed to the enclosing class instance and cannot be reassigned by how you call a method.

Clarifying questions expected:

  • "Should I focus on the conceptual model here, or would you rather I walk through the exact binding-rule priority order?" (the precise rules have their own dedicated question)

Code / implementation expected: Yes -- a short, runnable snippet showing one function reference producing three different this values depending on how it is called.

  • this
  • context
  • functions
  • scope

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read Β· 7 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptOne function, three call-sites, three different this values (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 48 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How does the fetch API work?

Continue