[thelist] [JavaScript] typeof() and properties of nonexistent array keys

liorean liorean at gmail.com
Thu Feb 8 18:57:51 CST 2007


On 08/02/07, Paul Bennett <Paul.Bennett at wcc.govt.nz> wrote:
> Accessing a nonexistent property, OR a nonexistent array key of an object using typeof() executes successfully and returns 'undefined'
> However, accessing and undefined property of an undefined array key causes the typeof() function to error out ('myObject[0] has no properties')and the script to stop executing
> My question is how is this different to trying to get the type of a non existent array key? After all, myObject has no properties when initialized, as I haven't given it any. What is it about the use of typeof in the second example that causes an error?

It's not about typeof at all. Execution doesn't get to the point of
applying the typeof operator in the second case. You see, typeof tests
what is the type of this object? And it can tell when it's got
nothing/undefined, when it's got an object of one of the primitive or
compound types.

However, the argument to typeof is object.nonexistentmember in one
case. That's okay, as I said, typeof can handle undefined. In the
other case however, the argument is
object.nonexistantmember.nonexistantmember. Here you're asking the
engine to get a member from an undefined, and undefined cannot have
members. So, the error is caused by the evaluation of the argument to
the typeof, not by the evaluation of typeof with that argument.
-- 
David "liorean" Andersson



More information about the thelist mailing list