Tuesday, 26 February 2013

Existing undefined properties

Well, it seems like there's always some new JavaScript trick to learn, probably that's why I love this language so much. I'll start with a question, and will answer it with what I learned today.

The access to a property can return undefined both when the property has the undefined value assigned (well, seems pretty obvious...) and when that property does not exist. I mean:

var obj = {
   name: undefined
}
obj.name === undefined; //true
obj.age === undefined; //true

So, how can we distinguish one case from the other?

Well, the first option that comes to my mind is using Object.getOwnProperty:

Object.getOwnProperty(obj, "name"); //returns a descriptor object
Object.getOwnProperty(obj, "age"); //returns undefined

and one second option would be using that new thing that I (mainly) found out today, the in operator. Yes, sure we all have used tons of times the for - in loop, but this in operator is quite unknown to most developers. Well, it returns true if one property exists (either in the object or in its prototype chain), irrespective of whether its value is null, undefined or whatever... and will return false if the property does not exist

>>> "name" in obj;
true
>>> "age" in obj;
false

No comments:

Post a Comment