Variable === Undefined VS. Typeof Variable === "Undefined"

variable === undefined vs. typeof variable === undefined

For undeclared variables, typeof foo will return the string literal "undefined", whereas the identity check foo === undefined would trigger the error "foo is not defined".

For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.

typeof a == 'undefined' vs typeof a === 'undefined'

In this instance, since typeof will always give you a string: It isn't better (nor is it worse). It makes no practical difference.

In general, using === is preferred because it forces you to be explicit about your types and saves you from getting results you don't expect when JavaScript's type resolution rules are unintuitive.

Is there any benefit of checking typeof a === undefined instead of a === undefined?

According to a related question undefined is not assured to be the thing you expect it to be:

var undefined = 'uh oh'

if (numLines === undefined) {
// Seems safe but isn't
}
else if (typeof(numlines) == 'undefined') {
// Actually gets it.
}

It's very odd that undefined is not nailed down in JavaScript, but that's how it is with the ECMA standard.

typeof !== undefined vs. != null

typeof is safer as it allows the identifier to never have been declared before:

if(typeof neverDeclared === "undefined") // no errors

if(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined

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

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.

Typeof operator returning undefined for everything but 'strings'

you are evaluating code in two different contexts: your module, where your variables exists with a value and in the console where they are undefined, hence the result you see. You can add to typeof in your script directly to see the correct result.

Why typeof undefined is return string?

Because that is how typeof works:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

if (a == undefined) { // instead its a type comparison 

How to check if a variable is undefined versus it is undeclared in javascript?

At least in the time of writing... No, it does not seem that you can do something like this:

var a = undeclared(var) ? 'undeclared' : 'undefined'

The reason is that you cannot pass an undeclared variable to a function; It raises an error, even in non-strict mode.

The best we can do, is this:

var barIsDeclared = true;

try { bar; }
catch (e) {
if (e.name == "ReferenceError") {
barIsDeclared = false;
}
}

console.log(barIsDeclared);


Related Topics



Leave a reply



Submit