“this” keyword in JavaScript

This is in my experience is most-asked question in any sort of JavaScript interview and very reasonably so. Hence absolutely need to master this concept.

‘this’ is just The JavaScript context object in which the current code is executing. In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.

Inside a function, the value of this depends on how the function is called.

Case-1 — WITHOUT STRICT MODE:

If a function is not in strict mode, and if the value of this is not set by the call, this will default to the global object, which is window in a browser or global in Node environment

Case-2 — WITH STRICT MODE:

However, the value of this remains at whatever it was set to when entering the execution context, ‘this’ will default to undefined. So, in strict mode, if this was not defined by the execution context, it remains undefined. The global object refers to ‘undefined’ in place of the windows object.

// Case-1 - WITHOUT STRICT MODE - Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser, or global in node environment.

function f1() {
  return this === global
}
console.log(f1()) // => true
// In a browser:
f1() === window // true
// In Node:
f1() === global // true
// Case-2 - In strict mode, however, the value of this remains at whatever it was set to when entering the execution context, so, in the following case, this will default to undefined. So, in strict mode, if this was not defined by the execution context, it remains undefined. And also, f2 was called directly and not as a method or property of an object (e.g. window.f2())
function f2() {
  "use strict"
  return this === undefined
}
console.log(f2()) // true

#coding #webdev #javascript #programming #interview

Tackling common JavaScript Interview Questions
1.40 GEEK