Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

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

Is there any differences between

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

Which one should we use?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...