talles
talles

Reputation: 15086

Are these undefined checking identical in behavior?

I've seem different approaches for (strict equality) checking for undefined:

In a happy scenario their behavior is the same. In other words, they all work.

But, considering all the quirk corners of JavaScript, are they truly identical in behavior?

If yes, why people choose other approaches rather than the first? Is it some sort of legacy or misconception? Because the first one it's obviously the most clear in both readability and intention demonstration.

Upvotes: 0

Views: 59

Answers (2)

elclanrs
elclanrs

Reputation: 94101

  1. Literally undefined
  2. Test for existence, as in "variable not declared".
  3. Same as undefined. Older version of the JS standard let you change the value of undefined as it's just a variable. void 0 is undefined, it's safer.

An extra one:

  1. if (x == null). Tests for undefined and null because undefined == null but remember, undefined !== null

In JavaScript there's a type 'undefined' and a value undefined. The value undefined is of type 'undefined'.

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382112

if (something === undefined) is the standard normal way

typeof something === 'undefined' on a declared variable is mostly an overdefensive solution dating from the time where you could change window.undefined. If you don't know if your variable is declared, it has the advantage of not raising an error but I don't think a legit code should support the case of a variable whose declarative state is unknown.

void 0 (or void anything) is a normalized way to get undefined so it's equivalent to the first one but useless.

Upvotes: 3

Related Questions