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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With