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

Lee kowalkowski lee.kowalkowski at googlemail.com
Thu Feb 8 17:01:17 CST 2007


On 08/02/07, Paul Bennett <Paul.Bennett at wcc.govt.nz> wrote:
> 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
> Eg:
> Var myObject = new Object();
> Alert(typeof(myObject[0].myUndefinedProperty));
>
> 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?

Firstly, typeof is not a function, it's an operator so it's just
"typeof myObject[0]" - but this is not the reason you can't do what
you're trying.

When the code is evaluated, the dot operator takes precedence, it
cannot evaluate the property of an object that does not exist
therefore does not get the chance to perform the typeof.

For the same reason, you couldn't then go ahead and do:
  myObject[0].myUndefinedProperty = foo;.

You'd have to do a myObject[0] = new Object() first.  You could use
the object literal: myObject[0] = {myUndefinedProperty:foo;};


So:
  if(myObject[0])
    alert(typeof myObject[0].myUndefinedProperty);

-- 
Lee



More information about the thelist mailing list