5

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.

Peter Krebs
  • 3,831
  • 2
  • 15
  • 29
  • `if (undefined)` is the same as `if (false)`. No error will result, if that's what you mean by "fail". – Pointy Feb 11 '22 at 15:43
  • 4
    Note that this is something you could have tested in your browser console in less time than it took to type in the question. – Pointy Feb 11 '22 at 15:44
  • please edit your title. No one would ever search for this title in the future, defeating any potential benefit to the larger community. – The Fool Feb 11 '22 at 15:44
  • 1
    `this` can be `undefined` in some cases. Like inside an arrow function, for example. – Louys Patrice Bessette Feb 11 '22 at 15:45
  • `(function () { "use strict"; return this === void 0; })()` – user3840170 Feb 11 '22 at 16:02
  • Since you seem curious about JavaScript, you may enjoy the video [WTFJS](https://www.youtube.com/watch?v=et8xNAc2ic8) and [these code examples](https://github.com/denysdovhan/wtfjs). – pyb Feb 11 '22 at 16:05
  • `this` can also be a primitive (other than `undefined`): `"use strict"; (function(){ if(this){ console.log("Truthy"); } else { console.log("Falsy"); } }).call(false);` logs `"Falsy"`. Even without strict mode, [falsy objects](//developer.mozilla.org/docs/Web/API/Document/all) are possible: `(function(){ if(this){ console.log("Truthy"); } else { console.log("Falsy"); } }).call(document.all);` logs `"Falsy"` in modern browsers. – Sebastian Simon Feb 25 '22 at 14:06
  • @pyb Meh, this talk has several mistakes and is quite outdated. I wouldn’t recommend it. – Sebastian Simon Feb 25 '22 at 14:10

1 Answers1

2

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

pyb
  • 4,813
  • 2
  • 27
  • 45