Xitcod13
Xitcod13

Reputation: 6079

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

Upvotes: 1

Views: 125

Answers (5)

achow
achow

Reputation: 1025

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)

Upvotes: 0

tskuzzy
tskuzzy

Reputation: 36446

"" 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

Upvotes: 4

RobG
RobG

Reputation: 147363

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.

Upvotes: 2

Alex Wayne
Alex Wayne

Reputation: 187014

"" 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.

Upvotes: 1

Ming-Tang
Ming-Tang

Reputation: 17651

There are types in JavaScript

typeof("") is "string" and typeof(null) is "object"

Upvotes: 1

Related Questions