2

Possible Duplicate:
JavaScript property access: dot notation vs. brackets?

<script>      
  var foo = {          
    name: 'kevin'        
  };

  document.write(foo.name);
  document.write(foo['name']);

  var cool = 'name';
  document.write(foo.cool);

  document.write(foo[cool]);      
</script>
  1. Why does foo.cool returns me undefined where as foo[cool] returns me kevin.
  2. How does cool actually refer to my name property in foo object.
Community
  • 1
  • 1
Kevin
  • 23,174
  • 26
  • 81
  • 111
  • 3
    Because the `[]` notation is used when the object property is an expression, like your variable `cool` (or contains characters that cannot be used with the `.` notation). If you use the `.` notation, the property cannot be the result of an expression. – Michael Berkowski Dec 29 '12 at 22:45

3 Answers3

4
  1. A cool property is not defined on foo, so foo.cool is undefined. If you did foo.name, it would return kevin.

  2. cool in foo[cool] is the one you defined in the line above it, so it is actually foo['name'], which is defined and has the value kevin.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • But var cool = 'name' is a string variable. How come JS associates it with the foo object just calling in the [] notation. – Kevin Dec 29 '12 at 22:49
  • @Kevin - It doesn't. You are accessing the property of `foo` that has the tag `name`, but are passing in the variable holding this value (namely, the variable `cool` holding the value `name`). `name` is what's associated. – Oded Dec 29 '12 at 22:50
1

You can access the properties either...

  • Literally by their name: property.name

  • Indirectly by an expression that evaluates to their name: property[expr].

Hence if the expression cool has value 'name', then foo[cool] is the same as foo['name'] or foo.name.

The brackets also allow for...

1) more complex expressions like foo["data_"+variable] to easily access fields named like data_something,
2) property names that aren't simple identifiers, for example you could say foo["I'm long!"].

I hope this explanation brightens things up for you.

Kos
  • 70,399
  • 25
  • 169
  • 233
1

In var foo = { name: 'kevin'}; You store an object or a dictionary to that variable... which is now a key-value pair... so you can access the value of an object using the key...

since its a key value pair... you can't access it using '.' operator... because foo is not a class... type of foo will be a dictionary or object...

so, to access the value you need to use the [] paranthesis...