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
There are types in JavaScript
typeof("") is "string" and typeof(null) is "object"
typeof null returns object, null is the Null type"" 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.
null means this identifier has no value. undefined means this identifier does not exist. There is a subtle but important difference there.var a; alert(a); shows undefined, yet a exists before the code executes—it just doesn't have a value. There are plenty of other examples.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)
if (variableName) where you are expecting the value to not be falsey. You can't use it reliably to detect the existence of a property or variable.
variable == ''evaluates to true then the value of variable might be an empty string, the number zero or boolean false, none of which will evaluate to true if compared with null.