Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does JSLint recommend x === "undefined" vs. typeof x == "undefined"?

I'm confused with JSLint.

My code originally checked if div:jqmData("me") was undefined like so:

if ( typeof el.jqmData("me") == "undefined"  
   ? el.not(':jqmData(panel="main")').length > 0 
    : el.not(':jqmData(me="first")').length > 0 ){

}

JSLint complains that I should replace checking with typeof with ===, so I did like this:

if ( el.jqmData("me") === "undefined"  
   ? el.not(':jqmData(panel="main")').length > 0 
     : el.not(':jqmData(me="first")').length > 0 ){

}

JSLint doesn't complain anymore, but my nested if statement is broken, because I'm now always ending up with the 2nd if el.not(':jqmData(me="first")').length even when I should not.

Question:
Why does JSLint recommend === over typeof == undefined? How comes this breaks my logic?

Thanks for some enlightment...

like image 706
frequent Avatar asked Nov 02 '12 22:11

frequent


People also ask

Why typeof undefined is undefined?

variable === undefined VS typeof variable === “undefined” Here the assigned variables don't have any value but the variable exists. Here the type of variable is undefined.

What is the value of typeof undefined === typeof null?

The typeof undefined is the string "undefined" — and undefined is a falsy value that is loosely equal to null but not to other falsy values.

How do you know if typeof is undefined?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

How do you compare undefined variables?

In modern browsers you can safely compare the variable directly to undefined : if (name === undefined) {...} After that re-assignment, comparing with undefined directly would no longer correctly detect whether a variable was assigned a value. The value of undefined is undefined (see 8.1).


1 Answers

You've broken the comparison logic. It's assumed you use

typeof el.jqmData("me") === "undefined"  

or

el.jqmData("me") === undefined

Personally I'd go with the latter.

And personally I think that this particular JSLint check in this particular case makes not much sense.

like image 122
zerkms Avatar answered Oct 14 '22 00:10

zerkms