Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is !== "" is not equal to !== null

Recently in JavaScript i have picked up the habit of using

if(data !== "")

to check if the data is null || undefined || blank string.

When i try to use

if(data !== null)
   //work here

Resharper throws a horrible error at me saying that the

"qualifier can be null or undefined"

enter image description here

I have added a jFiddle just to clarify : JsFiddle

My question is: Is this a ReSharper error or is there something behind this ?

like image 276
Pogrindis Avatar asked Jun 25 '14 16:06

Pogrindis


3 Answers

First of all, your habit is wrong. Using:

if(data !== "")

Will only check for an empty string. If data is undefined or null, the if block will still execute because !== checks for equality without performing any type conversions.

Secondly, ReSharper does not have an issue. It's trying to tell you that you may be making a mistake. if(data !== null) will only check against null. undefined and an empty string will still return true and cause the block to execute. ReSharper is warning you that you may be making a mistake (because rarely do you ever need to check for just null).

Just remember that undefined !== null !== "". You could attempt several of the shortcuts that are being mentioned but if you really want your code to be thorough, just check all three. If you're worried about code being too long, move the check to a utility method:

function hasValue(var data) {
    return (data !== undefined) && (data !== null) && (data !== "");
}
like image 58
Justin Niessner Avatar answered Oct 16 '22 23:10

Justin Niessner


In short, a var is null when it's not pointing anywhere. In the other hand, a var equal to "" is a defined var pointing to a variable which contains an empty string. That's essentially different.

[EDIT] As @jfriend00 correctly points out, null is a specific value in javascript. The difference would be then that null is a different value than "", which is an empty string and therefor not null.

The correct value for a var which is not initialized is undefined.

like image 5
BenSorter Avatar answered Oct 17 '22 00:10

BenSorter


Null and undefined can be treated in the same way

if (typeof data === "undefined") will return true if the data is undefined (or null), so

if (typeof data !== "undefined")

will return true if the data has been defined (so is not null), then you can check if it is an empty string,

if (data.length == 0)

will return true if the string is empty.

like image 1
theonlygusti Avatar answered Oct 16 '22 23:10

theonlygusti