Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to compare a value against 'undefined'?

Tags:

javascript

Is there any differences between

var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")

Which one should we use?

like image 254
JohnJohnGa Avatar asked Aug 18 '11 13:08

JohnJohnGa


2 Answers

Ironically, undefined can be redefined in JavaScript, not that anyone in their right mind would do that, for example:

undefined = "LOL!";

at which point all future equality checks against undefined will yeild unexpected results!

As for the difference between == and === (the equality operators), == will attempt to coerce values from one type to another, in English that means that 0 == "0" will evaluate to true even though the types differ (Number vs String) - developers tend to avoid this type of loose equality as it can lead to difficult to debug errors in your code.

As a result it's safest to use:

"undefined" === typeof a

When checking for undefinedness :)

like image 126
JonnyReeves Avatar answered Nov 15 '22 17:11

JonnyReeves


I personally like to use

[undefined, null].indexOf(variable) > -1

to check also for null values.

like image 27
Manuel Graf Avatar answered Nov 15 '22 15:11

Manuel Graf