开发者

What is the best JS practice to check undefined variable? [duplicate]

开发者 https://www.devze.com 2023-03-30 19:49 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: Javascript: undefined !== undefined?
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Javascript: undefined !== undefined?

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

开发者_Python百科

I've played around with the console and got some strange results when checking undefined,

when I do var a; a's type and value become "undefined" right? So why a===undefined is true and a=="undefined" or a==="undefined" are false?

and, would typeof a == "undefined" be the best practice like in other languages?

Unrelated - how do I markup code in a question from iPhone?


When doing a=="undefined" or a==="undefined" you're comparing the value of a with a string which contains the characters u, n, d, e, f, i, n, e, d.

So your expression boils down to undefined=="somestring", which is obviously false.

typeof returns a string, so in this case comparing it to a string works.


I suppose the best way is to perform strict equation check like a === undefined while typeof a == 'undefined' is overkill since there are no (at least as I know) situation which can lead to evaluating a === undefined to false while a is actually have a value of undefined.

I think comparsion of strings and taking typeof from variable is much slower than a strict equation (possibly speed tests needed).

Considering situation expression a itself is suitable way to check a for undefined value except for cases in which you need to handle false value of variable.


=== means compare type and value in Javascript. So

0 == '0' // true, because it is essentially toStringing both values
0 === '0' // false, because one is a Number and one is a String

When you check for a == "undefined" You are seeing if a is equal to the String value "undefined". undefined without quotes in Javascript is an undefined value. a === undefined compares a to the value undefined, and a === "undefined" compares a to the string "undefined".

Using a === undefined is a good practice for checking for definition

edit: this answer has some flaws, which I leave to the commenters to correct me


Just to cover one point: The word "undefined" is not special in javascript. There is no keyword or global representing it.

So when you do a === undefined it returns true because neither name has any value assigned to it - if you had somewhere previously created and assigned a variable with that name (like undefined = 1) then that statement would be false.

0

精彩评论

暂无评论...
验证码 换一张
取 消