Skip to main content
Post Closed as "Duplicate" by dsgriffin, Barmar, Niko, duri, Kris
edited title
Link
Niels B.
  • 6.4k
  • 4
  • 30
  • 45

JavaScript objects - [] vs dot

Source Link
Niels B.
  • 6.4k
  • 4
  • 30
  • 45

JavaScript objects - [] vs

What is the difference, if any, between these two assignments:

var foo = {}; foo['bar'] = "some value"; foo.baz = "some other value"; console.log(foo.bar) => "some value" console.log(foo.baz) => "some other value" 

Are they synonymous? I've noticed you can add keys with the [] syntax that are not valid property names.

foo['a space'] = "does not work"; console.log(foo.a space); => SyntaxError: Unexpected identifier 

My reason for asking is that I've cooked up a little JS library for pseudo namespacing. It is written on the assumption that the above assignments are identical (ignoring the superset allowed when using [] syntax)