Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript objects - [] vs dot [duplicate]

Tags:

javascript

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)

like image 782
Niels B. Avatar asked Jun 09 '26 14:06

Niels B.


1 Answers

foo["bar"] is equivalent to foo.bar, although foo.bar is easier to read in my opinion. As you already noticed the former syntax (foo["bar"]) allows you to use property names that are not valid identifiers. It also allows you to use dynamic property names:

var name = "bar";

foo[name] = 1;

console.log(foo["bar"]);

will output 1.