syntax - JavaScript property access: dot notation vs. brackets? -
other obvious fact first form use variable , not string literal, there reason use 1 on other, , if under cases?
in code:
// given: var foo = {'bar': 'baz'}; // var x = foo['bar']; // vs. var x = foo.bar;
context: i've written code generator produces these expressions , i'm wondering preferable.
(sourced here.)
square bracket notation allows use of characters can't used dot notation:
var foo = myform.foo[]; // incorrect syntax var foo = myform["foo[]"]; // correct syntax
secondly, square bracket notation useful when dealing property names vary in predictable way:
for (var = 0; < 10; i++) { somefunction(myform["mycontrolnumber" + i]); }
roundup:
- dot notation faster write , clearer read.
- square bracket notation allows access properties containing special characters , selection of properties using variables
another example of characters can't used dot notation property names contain dot.
for example json response contain property called bar.baz
.
var foo = myresponse.bar.baz; // incorrect syntax var foo = myresponse["bar.baz"]; // correct syntax
Comments
Post a Comment