Difrrence between null and "" in javascript
I have a simple if statement
if(variable == null)
does not enter the statement
if(variable == "")
does
Why does this happen?? What is the difference between "" and开发者_运维技巧 null in javascript
""
is the empty string. In other words, it's a string of length 0. null
on the other hand is more like a generic placeholder object (or an object representing the absence of an object). There's also undefined
which is different from both ""
and null
.
But the point is, "" != null
so therefore:
var s = "";
s == null; // false
s == ""; // true
The ECMA–262 Abstract Equality Comparison Algorithm (§ 11.9.3) says that null == null
(step 1.b) or null == undefined
(steps 2 and 3) return true
, everything else returns false.
There are types in JavaScript
typeof("") is "string" and typeof(null) is "object"
""
is a string object with a length of zero. null
is the value the represents the absence of a value. A string object is never null, regardless of its length.
As SHiNKiROU mentioned, there are types in Javascript. And since the language is dynamically typed, variables can change type. Therefore, even though your variable may have been pointing to, say, an empty string at some point, it may be changed to point to, say, a number now. So, to check the concept of "nonexistence" or "nothingness" or "undefinededness" of a variable, Crockford recommends against doing stuff like if (variableName == null)
.
You can take advantage of javascript's dynamically-typed qualities. When you want to check for a variable's "falsiness" or "nothingness", instead of if(variableName == null)
(or undefined
or ""
) use if(!variableName)
Also, instead of if(variableName != undefined)
(or null
or ""
) use if(variableName)
精彩评论