Are these undefined checking identical in behavior? - javascript

I've seem different approaches for (strict equality) checking for undefined:
if (something === undefined)
if (typeof something === 'undefined')
if (something === void 0)
and probably others
In a happy scenario their behavior is the same. In other words, they all work.
But, considering all the quirk corners of JavaScript, are they truly identical in behavior?
If yes, why people choose other approaches rather than the first? Is it some sort of legacy or misconception? Because the first one it's obviously the most clear in both readability and intention demonstration.

if (something === undefined) is the standard normal way
typeof something === 'undefined' on a declared variable is mostly an overdefensive solution dating from the time where you could change window.undefined. If you don't know if your variable is declared, it has the advantage of not raising an error but I don't think a legit code should support the case of a variable whose declarative state is unknown.
void 0 (or void anything) is a normalized way to get undefined so it's equivalent to the first one but useless.

Literally undefined
Test for existence, as in "variable not declared".
Same as undefined. Older version of the JS standard let you change the value of undefined as it's just a variable. void 0 is undefined, it's safer.
An extra one:
if (x == null). Tests for undefined and null because undefined == null but remember, undefined !== null
In JavaScript there's a type 'undefined' and a value undefined. The value undefined is of type 'undefined'.

Related

What is the better way to check if a variable is undefined? [duplicate]

I've seem different approaches for (strict equality) checking for undefined:
if (something === undefined)
if (typeof something === 'undefined')
if (something === void 0)
and probably others
In a happy scenario their behavior is the same. In other words, they all work.
But, considering all the quirk corners of JavaScript, are they truly identical in behavior?
If yes, why people choose other approaches rather than the first? Is it some sort of legacy or misconception? Because the first one it's obviously the most clear in both readability and intention demonstration.
if (something === undefined) is the standard normal way
typeof something === 'undefined' on a declared variable is mostly an overdefensive solution dating from the time where you could change window.undefined. If you don't know if your variable is declared, it has the advantage of not raising an error but I don't think a legit code should support the case of a variable whose declarative state is unknown.
void 0 (or void anything) is a normalized way to get undefined so it's equivalent to the first one but useless.
Literally undefined
Test for existence, as in "variable not declared".
Same as undefined. Older version of the JS standard let you change the value of undefined as it's just a variable. void 0 is undefined, it's safer.
An extra one:
if (x == null). Tests for undefined and null because undefined == null but remember, undefined !== null
In JavaScript there's a type 'undefined' and a value undefined. The value undefined is of type 'undefined'.

Best practice of checking if variable is undefined

I was having some issues in my conditions concerning undefined variables. What is, to sum it up, the best way to check if a variable is undefined?
I was mainly struggling with
x === undefined
and
typeof x === 'undefined'
You can use both ways to check if the value is undefined. However, there are little nuances you need to be aware of.
The first approach uses strict comparison === operator to compare against undefined type:
var x;
// ...
x === undefined; // true
This will work as expected only if the variable is declared but not defined, i.e. has undefined value, meaning that you have var x somewhere in your code, but the it has never been assigned a value. So it's undefined by definition.
But if variable is not declared with var keyword above code will throw reference error:
x === undefined // ReferenceError: x is not defined
In situations like these, typeof comparison is more reliable:
typeof x == 'undefined' // true
which will work properly in both cases: if variable has never been assigned a value, and if its value is actually undefined.
I guess both, depending on what you're testing? If it's a property, I'd always use x === undefined, since it's clearer (and it seems faster).
As others said, x === undefined won't work if x is not declared. Personally, I find that an even better reason to use it, since normally I shouldn't be checking if a variable is declared at all — it would usually be a sign of a coding mistake.
I've seen a lot of the other version for testing arguments — f = function(x) {if (typeof x == 'undefined') …} — if I'm code-reviewing code like this I'll tell them to change it. We know for a fact the variable is declared, and making an habit of writing it that way increases the chance you'll waste time chasing typo bugs.
The main exception is when you're trying to check if a component or library was loaded or initialized correctly. if (typeof jQuery == 'undefined') … makes sense. But in the medium term, all this should become modules anyway, in which case the typeof test should in my opinion be phased out as harmful.
(Also, personally, I prefer if (window.jQuery === undefined) for that case too. It's not portable for isomorphic code, though.)
x === undefined
does not work if variable is not declared. This returns true only if variable is declared but not defined.
Better to use
typeof x === 'undefined'
You could use any of them.
If you would like to check if a variable is undefined or null you could use:
x == null
This results in true if x is undefined or null.

Javascript module pattern with undefined specified

I believe jQuery uses undefined in the module pattern to avoid it being redefined to an unexpected value. I thought about doing this but whenever I compare undefined I tend (always?) to use
typeof foo === 'undefined'
So is there any point doing this:
(function (win, doc, RG, undefined)
{
// App goes here
})(window, document, typeof RGraph === 'object' ? RGraph : {});
whenever I compare undefined I tend (always?) to use typeof foo === 'undefined'
Well if you don't use undefined in your module then there is no point in declaring it as a parameter to ensure its value.
However, there's a question mark after your "always", and you can hardly know who else might work with your code in the future, so it still might be advisable.
There are three ways to test whether a value is undefined:
Method 1: Use typeof:
if (typeof value === "undefined") {
// do something
}
Method 2: Compare it with the variable undefined:
if (value === undefined) {
// do something
}
Method 3: Compare it with void 0:
if (value === void 0) {
// do something
}
Q: Which one should you use?
A: There are many factors to consider:
In terms of understandability typeof and undefined are the best.
In terms of minimum characters undefined is the best when minified.
In terms of performance (http://jsperf.com/type-of-undefined-vs-undefined):
Both undefined and void are at par in most browsers (notably Firefox and Chrome).
In Chrome typeof is slower than the other two but in Firefox it is the fastest.
Using typeof is the only way to test whether or not a variable exists.
Based on these factors I would say that undefined (method 2) is the best method. There's always the problem of undefined being overwritten. However if you're using the module pattern (which you should be doing in the browser) then you can get undefined for free:
(function ($, undefined) {
// you can use `undefined` safely here
}(jQuery));
Hence if you're using the module pattern then I would suggest you use the second method. It is readable, understandable and concise. The only disadvantage is that you won't be able to test whether or not a variable exists. However you can always fall back to typeof for that.

In Javascript, is myObject == null a valid way to handle checking for undefined as well?

In Javascript, is myObject == null a valid way to handle checking for undefined as well as null?
JSLint would prefer that I do (myObject === undefined || myObject === null)
What Would Doug Crockford Do? (WWDCD)
Yes, that's a nice way to check for both. The language specification states (regarding == for comparing values of different types):
2) If x is null and y is undefined, return true.
3) If x is undefined and y is null, return true.
Here x and y are the terms of a comparison x == y. When you're comparing x == null, it will only be true if x is undefined, or null itself.
Just to be clear, when we say "undefined" here we mean the value undefined, not variables that are not defined (those produce a ReferenceError whenever they're used, except with typeof).
And regarding WWDCD, I'll quote Ian: Crockford would suggest what JSLint suggests (obviously) because == is voodoo to him. That means "use ===, never ==". So this would be a non-question for him.
Is myObject == null a valid way to handle checking for undefined as well as null?
Yes. As defined by the specification, null and undefined are the only two values that equal null.
JSLint would prefer that I do (myObject === undefined || myObject === null)
Then it doesn't understand your intention. It's not the first time. Or it (and its creator Crockford) want you to write explicit code, to be correctly understood by everyone who doesn't know all of Javascript's internals.
Running this code:
<html>
<head>
<script type="text/javascript">
function test() {
var variable = undefined;
if (typeof variable === 'undefined') console.log("variable is undefined");
if (variable == null) {
console.log("variable is null");
} else {
console.log("variable is not null");
}
}
</script>
</head>
<body onLoad="test()">
</body>
Returned the output
variable is undefined
variable is null
So... it seems to work. But I also seem to remember something odd about null vs undefined. Or maybe that was in another language-they start to blur together after a while.
Regardless, the answer that #collapsar gave is probably the cleanest way to do it as it checks for all cases.

localStorage alerts undefined but if undefined is false

Can not quite understand the reasoning for this. In the following code the localStorage of an item is alerted as undefined, but if I use an if(x==undefined) syntax it does not work. Can somebody explain what is the problem. Thank you.
alert(localStorage["x"]);
if(localStorage["x"]=="undefined"){alert("y");}
The top line alerts undefined
The bottom line does not alert y for me.
It doesn't contain the string "undefined", it contains a value of the type undefined:
if (localStorage["x"] == undefined) { alert("y"); }
The value undefined is possible to change in older browsers, so good practice is to check the type instead:
if (typeof localStorage["x"] == 'undefined') { alert("y"); }
Try:
if(typeof( localStorage["x"]) == 'undefined'){alert("y");}
OR
if( localStorage["x"] == undefined){alert("y");}
OR
if( !localStorage["x"] ){alert("y");}
The two ways of checking for something being undefined are:
typeof foo === "undefined"
and
foo === undefined
In the first case, it will be true if foo was never defined or the value of foo is undefined.
In the second case, it will only be true if foo was defined (otherwise it'll break) and its value is undefined.
Checking its value against the string "undefined" is not the same at all!
UPDATE:
When I said that if you try to perform an operation on an object literal's property that isn't defined, I guess I meant if it's undefined at all, and what I meant was something more like this:
obj["x"].toLowerCase()
// or
obj["x"]["y"]
where you are attempting to access/operate on something that is originally undefined. In this case, simply comparing in an if statement should be fine, because of the way object literals report the value...but is very different with normal Javascript variables.
With object literals, if a key (say "x") is not defined, then
obj["x"]
returns a value of undefined, so both the typeof and basic === undefined checks will work and be true.
The whole difference of not being defined or having a value of undefined is different with normal variables.
If you had:
var a;
// or
var a = undefined;
then both the typeof and basic === undefined checks I provided earlier would work and be true. But if you never even declared a, then only the typeof check would work and be true. The === undefined check would break.
Take a look at: http://jsfiddle.net/7npJx/
If you notice in the console, it says b is not defined and breaks the if statement.
Since you're basically looking at an object literal with localStorage, the way to distinguish whether an item is not defined or has a value of undefined is to use in first. So, you could use:
if (!("x" in localStorage)) {
to check if "x" is not a defined property at all, and:
else if (localStorage["x"] === undefined) {
to then check if it is defined but has a value of undefined. Then, using:
else {
would signify that localStorage["x"] is both defined and does not have the value undefined.
In your code though, it's okay to use the typeof or in checks (based on what you want to know) because of the way object literals report properties that aren't defined. Using the basic === undefined is also okay, but as Guffa pointed out, it's possible for the actual value of undefined to be overwritten and then wouldn't work in this comparison. When it comes to normal Javascript variables, typeof and === undefined checks aren't the same.

Categories

Resources