Sample problem:
Other than the obvious fact that the first form could use a variable and not just a string literal, is there any reason to use one over the other, and if so under which cases?
In code:
// Given:
var foo = {'bar': 'baz'};
// Then
var x = foo['bar'];
// vs.
var x = foo.bar;
Context: I’ve written a code generator that produces these expressions and I’m wondering which is preferable.
JavaScript property access: dot notation vs brackets- Answer #1:
Square bracket notation allows the use of characters that can’t be used with dot notation:
var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax
including non-ASCII (UTF-8) characters, as in myForm["ダ"]
.
Secondly, square bracket notation is useful when dealing with property names which vary in a predictable way:
for (var i = 0; i < 10; i++) {
someFunction(myForm["myControlNumber" + i]);
}
Roundup:
- Dot notation is faster to write and clearer to read.
- Square bracket notation allows access to properties containing special characters and selection of properties using variables
Another example of characters that can’t be used with dot notation is property names that themselves contain a dot.
For example a json response could contain a property called bar.Baz
.
var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax
Answer #2:
The bracket notation allows you to access properties by name stored in a variable:
var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello
obj.x
would not work in this case.
Answer #3:
The two most common ways to access properties in JavaScript are with a dot and with square brackets. Both value.x
and value[x]
access a property on value—but not necessarily the same property. The difference is in how x is interpreted. When using a dot, the part after the dot must be a valid variable name, and it directly names the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.
So if you know that the property you are interested in is called “length”, you say value.length
. If you want to extract the property named by the value held in the variable i
, you say value[i]
. And because property names can be any string, if you want to access a property named “2”
or “John Doe”
, you must use square brackets: value[2]
or value["John Doe"]
. This is the case even though you know the precise name of the property in advance, because neither “2”
nor “John Doe”
is a valid variable name and so cannot be accessed through dot notation.
In case of Arrays
The elements in an array are stored in properties. Because the names of these properties are numbers and we often need to get their name from a variable, we have to use the bracket syntax to access them. The length property of an array tells us how many elements it contains. This property name is a valid variable name, and we know its name in advance, so to find the length of an array, you typically write array.length
because that is easier to write than array["length"]
.
Answer #4:
Dot notation does not work with some keywords (like new
and class
) in internet explorer 8.
I had this code:
//app.users is a hash
app.users.new = {
// some code
}
And this triggers the dreaded “expected indentifier” (at least on IE8 on windows xp, I havn’t tried other environments). The simple fix for that is to switch to bracket notation:
app.users['new'] = {
// some code
}
Answer #5:
Be careful while using these notations: For eg. if we want to access a function present in the parent of a window. In IE :
window['parent']['func']
is not equivalent to
window.['parent.func']
We may either use:
window['parent']['func']
or
window.parent.func
to access it.
Answer #6:
Both foo.bar
and foo["bar"]
access a property on foo but not necessarily the same property. The difference is in how bar
is interpreted. When using a dot, the word after the dot is the literal name of the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas foo.bar
fetches the property of value named “bar”
, foo["bar"]
tries to evaluate the expression "bar"
and uses the result, converted to a string, as the property name
Dot Notation’s Limitation
if we take this oject :
const obj = {
123: 'digit',
123name: 'start with digit',
name123: 'does not start with digit',
$name: '$ sign',
name-123: 'hyphen',
NAME: 'upper case',
name: 'lower case'
};
accessing their propriete using dot notation
obj.123; // ❌ SyntaxError
obj.123name; // ❌ SyntaxError
obj.name123; // ✅ 'does not start with digit'
obj.$name; // ✅ '$ sign'
obj.name-123; // ❌ SyntaxError
obj.'name-123';// ❌ SyntaxError
obj.NAME; // ✅ 'upper case'
obj.name; // ✅ 'lower case'
But none of this is a problem for the Bracket Notation:
obj['123']; // ✅ 'digit'
obj['123name']; // ✅ 'start with digit'
obj['name123']; // ✅ 'does not start with digit'
obj['$name']; // ✅ '$ sign'
obj['name-123']; // ✅ 'does not start with digit'
obj['NAME']; // ✅ 'upper case'
obj['name']; // ✅ 'lower case'
accessing variable using variable :
const variable = 'name';
const obj = {
name: 'value'
};
// Bracket Notation
obj[variable]; // ✅ 'value'
// Dot Notation
obj.variable; // undefined
Answer #7:
You have to use square bracket notation when –
- The property name is number.
var ob = { 1: 'One', 7 : 'Seven' } ob.7 // SyntaxError ob[7] // "Seven"
- The property name has special character.
var ob = { 'This is one': 1, 'This is seven': 7, } ob.'This is one' // SyntaxError ob['This is one'] // 1
- The property name is assigned to a variable and you want to access the property value by this variable.
var ob = { 'One': 1, 'Seven': 7, } var _Seven = 'Seven'; ob._Seven // undefined ob[_Seven] // 7
Answer #8:
You need to use brackets if the property names has special characters:
var foo = {
"Hello, world!": true,
}
foo["Hello, world!"] = false;
Other than that, I suppose it’s just a matter of taste. IMHO, the dot notation is shorter and it makes it more obvious that it’s a property rather than an array element (although of course JavaScript does not have associative arrays anyway).
Hope you learned something from this post.
Follow Programming Articles for more!