Trivia Questions1 min readPremium

Explain how ‘this’ works in JavaScript

Demystifying ‘this’ in JavaScript

The keyword this in JavaScript is a fundamental concept that often confuses beginners. Its value is determined by how a function is called, making it a critical part of JavaScript’s object-oriented programming. Here, we explore the diverse scenarios affecting this and its practical applications. MDN’s this reference covers every binding rule.

Contextual Behavior of ‘this’

In different execution contexts, this can refer to distinct values. For example, in the global context, it typically points to the window object in browsers, while at the top level of a Node.js CommonJS module it is module.exports, and in ES modules it is undefined. However, inside functions, its value shifts based on strict mode and the function’s calling context.

Scenarios Impacting ‘this’

  • Global Context: this refers to the global object, like the window in browsers.
  • Function Context: In regular function calls, this can point to the global object or be undefined in strict mode.
  • Object Method Context: When a function is called as an object method, this refers to the object itself.
  • Event Handlers: In a regular function listener, this refers to the element the listener is attached to (event.currentTarget), which is not necessarily the element that... premium content.
Premium

Keep reading with Premium

Get the rest of this guide plus every premium question, solution, and system design deep dive.

  • All premium solutions
  • System design deep dives
  • Company-specific prep

4.9/5 from our users