Take this snippet,
var a = {
}
if(typeof a.c === 'undefined'){
console.log('inside if');
}
if(a.c === undefined){
console.log('inside if');
}
Both if results in true. Is there any difference in both statements specific to some browsers?
Also, in my last project I have already used typeof a.c == 'undefined' numerous times to check values in json data.
Now, I know that this is not good way, as some value may be undefined too, so my logic will fail.
I should have used hasOwnProperty .
But I am sure that no value will be undefined , can I use typeof a.c == 'undefined' in place of hasOwnProperty or should I change all my typeof with hasOwnProperty
(UPDATE: You might want to check out this question: variable === undefined vs. typeof variable === "undefined").
In very old browsers (Netscape 2, IIRC, and possibly IE 4 or lower), you couldn’t compare a value with
undefined, since that caused an error. In any (semi-) modern browser, however, there’s no reason to checktypeof value === 'undefined'instead ofvalue === undefined(except for paranoia that somebody might have redefined the variableundefined).hasOwnPropertyserves a different purpose. It checks if the object has a property with the given name, and not its prototype; i.e. regardless of the inherited properties. If you want to check whether an object contains a certain property, inherited or not, you should useif ('c' in a) {…But basically, these will probably all work:
The main differences being that:
a.c === undefinedwill produce an unexpected result if someone has doneundefined = 'defined'or some such trick;!('c' in a)is not very readable (IMHO)!a.hasOwnProperty('c')will returnfalseif the objectadoesn’t contain a propertyc, but its prototype does.Personally, I prefer the first since it’s more readable. If you’re paranoid and want to avoid the risk of a redefined
undefined, wrap your code in a self-executing anonymous function as follows: