Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Understanding 'this' in JavaScript

Master the 'this' keyword and its binding in different contexts.

jiocoder TeamUpdated Jun 6, 20261 min readJavaScript
Understanding 'this' in JavaScript

'this' in Different Contexts#

Global Context#

Code
console.log(this); // Window (browser) or global (Node.js)

Function Context#

Code
function regularFunction() {
  console.log(this); // Window (non-strict) or undefined (strict)
}

const obj = {
  name: 'John',
  greet: function() {
    console.log(this.name); // 'John'
  },
  arrow: () => {
    console.log(this); // Window (lexical this)
  }
};

Binding Methods#

Code
// call, apply, bind
const person = {
  name: 'John'
};

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

greet.call(person, 'Hello'); // "Hello, John"
greet.apply(person, ['Hi']); // "Hi, John"
const boundGreet = greet.bind(person);
boundGreet('Hey'); // "Hey, John"

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment