In javascript whats the difference between
undefined == variable and variable == undefined are both of them same? and how different will it be if i do undefined === variable or typeof variable == 'undefined'?
Can someone help me out
Don't use undefined to test for an undefined variable, use the typeof operator instead!
undefined isn't a javascript keyword, it's just a variable name. If someone writes var undefined = true globally anywhere into the code, all your comparisons will act unexpected.
You should consider using something like JSLINT or JSHINT to avoid these type of errors in your javascript code.
Apart from that, I would always write the compared parameter first, as that's the way I read it.
That is why If the variable foo is undefined than should be written as if (typeof foo === "undefined")
I don't remember the name for this pattern, but I'm quite sure there is one :)
There is no difference in meaning when it comes to different order of parts you mentioned.
=== is strict comparison, == is not. For example undefined == false is true, but undefined === false is not. Checking the undefined type is similar to strict comparison in this case.
undefined == variable and variable == undefined are the same.
but i recomment undefined == variable to prevent strange behalves if you miss a = (variable = undefined).
undefined === variable and typeof variable == 'undefined' should also be the same.
Related
I'm just wondering whats the correct way to check if a function is undefined with a script which will be closured in advanced mode and how to access global functions?
E.g. an example of checking if google analytics is loaded:
typeof window["ga"] == "function"
typeof window["ga"] !== "undefined"
But is the following bullet proof with closure compilers as well?
typeof window["ga"] == function
typeof window["ga"] !== undefined
And what about localStorage. Like magic the following works in chrome:
if (localStorage != undefined ) myvariabel = localStorage.getItem('myvariable')
But in seems to me like dirty coding. In my mind the following would be correct or?
if(typeof localStorage != "undefined")
// or even better the following since per definition local storage is an attribute of window:
if(typeof window["localStorage"] != "undefined") myvariabel = window["localStorage"].getItem('myvariable')
In this context is .getItem safe to use in advanced compiler mode or do I have to code:
if(typeof window["localStorage"] != "undefined") myvariabel = window["localStorage"]["getItem"]('myvariable')
The typeof operator will give you a string describing the type.
function is not a string, and expects to be followed by certain characters. typeof window["ga"] == function will therefore throw an exception.
typeof will always give you a string. A string is never an undefined value. typeof window["ga"] !== undefined will always give you a true result.
So no. Not using strings isn't bullet proof. Quite the opposite; it won't work anywhere.
And what about localStorage
This is no different to any other variable.
Like magic the following works in chrome
if (localStorage != undefined )
Now you are testing if the variable is equal to undefined, not if using typeof is. That's a completely different problem.
That will work… but only if:
undefined hasn't been masked by a different variable that is defined and
localStorage has been declared
If it hasn't been declared that you will get a ReferenceError and your script will abort (unless you are using try/catch).
So no. Never compare a variable directly to undefined.
There is a slim possibility that undefined isn't what you think it is. Most of the time you care about the variable being declared as well as being defined. And the rest of the time you can continue to use typeof because it works reliably everywhere and using it as a matter of habit is better then mixing and matching and sometimes getting it wrong.
I just read this excellent question and top answer on "== versus ===".
var x = undefined;
When checking if x is truly equal to undefined, both of the below worked.
if(typeof x == "undefined") {
console.log("typeof x == \"undefined\"");
}
if(x === undefined) {
console.log("x === undefined");
}
output:
typeof x == "undefined"
x === undefined
Is one way more idiomatic than the other? If so, why?
I would say if you have control over the the range of possible values of x then checking for x === undefined is the most idiomatic way. For instance, if you have a function that is returning a result, or undefined if it encounters an error.
Otherwise, you should use typeof x == 'undefined'.
The caveat is that some expressions and variables can be undefined because they are simply not defined, while others are explicitly defined as undefined.
If you try to do this:
var x = undefined;
if(typeof x == "undefined") // This works
if(x === undefined) // This works
if(typeof y == "undefined") // This works
if(y === undefined) // This does not work and throws a ReferenceError
So basically, using typeof is safer and easier if you don't have control over the variable's range because you don't have to implement exception handling.
Both the above conditional checks work, and therefore, can be used interchangeably. However, since you have asked about being idiomatic, I would say the conditional check: typeof x == undefined sounds better when reading and explains what the code really does, and hence, has my personal vote :)
if you use raw javascript you'd better do typeof x == "undefined", why?
because undefined is a global variable which, in some browsers is not read-only and anyone could override it, for instance, in Chrome 14, or Firefox 6 you can do:
window.undefined = "MyUndefined"
and this would override the undefined global variable, of course it seems so ridicules to do this or even to worry about this, but it is much more safer when you check your variables being undefined, like this:
typeof x == "undefined"
this is the main reason why I'm against using the undefined property.
and what this has anything to do with using raw javascript:
if you use jQuery, jQuery has overrided the global variable undefined with a real undefined value.
I want to check this:
if ( typeof myVar != "undefined" && myVar != null )
...
In other words, I want to check if a variable has a defined value (including 0 or an empty string), but not undefined or null, which I interpret as valueless.
Do I have to do the two-part check each time or is there a handy shortcut?
If you want to allow 0 and "" as valid values and you want to cover the case of the variable might not even be delcared, but don't consider null a valid value, then you have to specifically check for undefined and null like this:
if (typeof myVar !== 'undefined' && myVar !== null)
...
A lot of values are falsey (they don't satisfy if (myVar) so you really have to conciously decide which ones you're testing for. All of these are falsey:
undefined
false
0
""
null
NaN
If you want to allow some, but not others, then you have to do a more specific test than if (myVar) like I've shown above to isolate just the values you care about.
Here's a good writeup on falsey values: http://www.sitepoint.com/javascript-truthy-falsy/.
If you know the variable has been declared and you just want to see if it's been initialized with something other than null, you can use this:
if (myVar != undefined)
...
Using only the != instead of !== allows this to test for both undefined and null via type conversion. Although, I wouldn't recommend this because if you're trying to discern between falsey values, it's probably better to NOT let the JS engine do any type conversions at all so you can control exactly what it does without having to memorize all the type conversion equality rules. I'd stick with this to be more explicit:
if (typeof myVar !== 'undefined' && myVar !== null)
...
If you want to know if it has any non-falsey value, you can of course do this (but that won't allow 0 or "" as valid values:
if (myVar)
...
The 2-part method. If you don't check for the typeof first, you'll end up with a reference error.
If you know the context of myVar, you should be able to do this:
if (this.myVar != null) {
...
}
if myvar could be undefined, calling it without the typeof check will throw an error.
And if it is defined as null (like myvar= element.lastChild for an element with no children) you will miss catching it if you just use typeof.
Well, null is a defined value... so if you want to make sure that the variable doesn't contain null, and isn't undefined you must do both checks.
Could somebody explain to me the difference between if(obj.x == undefined) and if(typeof obj.x == 'undefined')
In some context the first one works fine, but in other I need to use the second way.
Questions
1 - What is the difference between the two condition?
2 - Is there a best practice?
The best practice is to not just check the truthiness but the strict equality
example
if (obj.x === undefined) {}
this use to be an issue because undefined (a global property) use to be writable, as of 1.8.5 is is non-writable, providing you with a secure comparison in ES5 spec environments.
per MDN
The two would usually be equivalent if you replaced the equality operator == with the strict equality operator ===. So obj.x === undefined and typeof obj.x == "undefined" are usually equivalent.
However, in pre-ECMAScript 5 environments (which still acount for the majority of web requests, in general), undefined is a writable property of the global object, meaning that undefined may be used as variable name or the global property may be assigned a different value. ECMAScript 5 makes the global property read-only, but even then, undefined may still be used as variable name within a function, meaning that the typeof check is always safer.
One further point in favour of typeof is that it may be used to check for a variable that may not have been declared whereas a direct comparison will throw a ReferenceError if the variable has not been declared. For example:
typeof foo == "undefined" // true
foo === undefined // ReferenceError
However, this is an unusual and not generally helpful thing to be doing.
The two are not equivalent tests because of the quite convoluted handling of special values by javascript. In the specific
undefined == null
is true, but typeof undefined is "undefined" while typeof null is "object".
The rules for those special values are quite complex and IMO illogical, so I think there's no "general rule". What you may find are common forms, for example
var value = obj.x || default_value;
that can be used if you're sure that obj will never be undefined or null (because in that case an exception would be thrown) and assuming that 0, NaN or an empty string should be considered as if no value was provided (because they're all "logically false" values). An empty array or an empty javascript object instead are considered "logically true".
Why is it that way? Why does (null).x throw an exception when null according to typeof is apparently an object and searching for a non-existent field in an object normally returns undefined instead?
I've no idea.
I never tried to find a logic in all those strange rules. I'm not actually even 100% sure there's one.
My suggestion is just to study and experiment with them.
second is easier and faster than first. First requires additional setup, definition of undefined and check wheter obj contains x as a property or method. second makes the check whether obj.x has been whenever defined and assigned
PS.: undefined will be evaluated to null so
obj.x == undefined is equivalent to obj.x == null
the best way to test for conditionality isusing obj.x this checks for both null-ability and undefined .
Thus
if(!obj.x)
{
alert(obj.x);
}
else
{
alert("obj.x is null or undefined"); //obj.x is null or undefined or any false value which is what you want. like obj.x is false or 0
}
The main difference of these two condition is typeof
The typeof operator is used to get the data type (returns a string) of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. The operator returns the data type.
if (typeof obj.x === 'undefined') {
txt = "x is undefined";
} else {
txt = "x is defined";
}
This question already has answers here:
What is the difference between null and undefined in JavaScript?
(38 answers)
Closed 8 years ago.
I am really confused as to when JavaScript returns null or undefined. Also different browsers seem to be returning these differently.
Could you please give some examples of null/undefined with the browsers that return them.
While I am now clear on the undefined aspect, I am still not 100% clear on null. Is it similar to a blank value?
E.g. You have a text box which does not have any value set. Now when you try to access its value, will it be null or undefined and are they similar?
I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.
var x;
x == null // true
x == undefined // true
x === null // false
x === undefined // true
var y = null;
y == null // true
y == undefined // true
y === null // true
y === undefined // false
typeof x // 'undefined'
typeof y // 'object'
var z = {abc: null};
z.abc == null // true
z.abc == undefined // true
z.abc === null // true
z.abc === undefined // false
z.xyz == null // true
z.xyz == undefined // true
z.xyz === null // false
z.xyz === undefined // true
null = 1; // throws error: invalid left hand assignment
undefined = 1; // works fine: this can cause some problems
So this is definitely one of the more subtle nuances of JavaScript. As you can see, you can override the value of undefined, making it somewhat unreliable compared to null. Using the == operator, you can reliably use null and undefined interchangeably as far as I can tell. However, because of the advantage that null cannot be redefined, I might would use it when using ==.
For example, variable != null will ALWAYS return false if variable is equal to either null or undefined, whereas variable != undefined will return false if variable is equal to either null or undefined UNLESS undefined is reassigned beforehand.
You can reliably use the === operator to differentiate between undefined and null, if you need to make sure that a value is actually undefined (rather than null).
According to the ECMAScript 5 spec:
Both Null and Undefined are two of the six built in types.
4.3.9 undefined value
primitive value used when a variable has not been assigned a value
4.3.11 null value
primitive value that represents the intentional absence of any object value
The DOM methods getElementById(), nextSibling(), childNodes[n], parentNode() and so on return null (defined but having no value) when the call does not return a node object.
The property is defined, but the object it refers to does not exist.
This is one of the few times you may not want to test for equality-
if(x!==undefined) will be true for a null value
but if(x!= undefined) will be true (only) for values that are not either undefined or null.
You get undefined for the various scenarios:
You declare a variable with var but never set it.
var foo;
alert(foo); //undefined.
You attempt to access a property on an object you've never set.
var foo = {};
alert(foo.bar); //undefined
You attempt to access an argument that was never provided.
function myFunction (foo) {
alert(foo); //undefined.
}
As cwolves pointed out in a comment on another answer, functions that don't return a value.
function myFunction () {
}
alert(myFunction());//undefined
A null usually has to be intentionally set on a variable or property (see comments for a case in which it can appear without having been set). In addition a null is of type object and undefined is of type undefined.
I should also note that null is valid in JSON but undefined is not:
JSON.parse(undefined); //syntax error
JSON.parse(null); //null
I might be missing something, but afaik, you get undefined only
Update: Ok, I missed a lot, trying to complete:
You get undefined...
... when you try to access properties of an object that don't exist:
var a = {}
a.foo // undefined
... when you have declared a variable but not initialized it:
var a;
// a is undefined
... when you access a parameter for which no value was passed:
function foo (a, b) {
// something
}
foo(42); // b inside foo is undefined
... when a function does not return a value:
function foo() {};
var a = foo(); // a is undefined
It might be that some built-in functions return null on some error, but if so, then it is documented. null is a concrete value in JavaScript, undefined is not.
Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable) to test whether a value is set or not (both, null and undefined evaluate to false).
Also different browsers seem to be returning these differently.
Please give a concrete example.
Regarding this topic the specification (ecma-262) is quite clear
I found it really useful and straightforward, so that I share it:
- Here you will find Equality algorithm
- Here you will find Strict equality algorithm
I bumped into it reading "Abstract equality, strict equality, and same value" from mozilla developer site, section sameness.
I hope you find it useful.
A property, when it has no definition, is undefined.
null is an object. It's type is null. undefined is not an object, its type is undefined.
This is a good article explaining the difference and also giving some examples.
null vs undefined