Does if(this) {} else {} ever visit the else in JavaScript?

Viewed 68

Is there any case where the condition if(this) {} fails? Because I couldn't think of a scenario where this is undefined.
This is not an important question nor something anyone would normally use, I'm just asking out of pure curiosity.

1 Answers

Yes, in some execution contexts, this is undefined, which is falsy in JavaScript:

In strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as shown in the following example:

Here is at least one convoluted scenario in which the following conditions must be met:

  • global or function execution in strict mode
  • the function was defined at the top-level (effectively being a function of window)
  • that function was called directly without invoking its parent (i.e. foo() and not window.foo())
  • the function returned this
function foo() {
  'use strict'; // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
  return this;
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Related