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 which produces these expressions and I'm wondering which is preferable.
(Sourced from here.)
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["ダ"] (more examples).
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
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.
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"].
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
}
Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like
var x = elem["foo[]"]; // can't do elem.foo[];
This can be extended to any property containing special characters.
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
You need to use brackets if the property name 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).
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
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
Bracket notation can use variables, so it is useful in two instances where dot notation will not work:
1) When the property names are dynamically determined (when the exact names are not known until runtime).
2) When using a for..in loop to go through all the properties of an object.
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Case where [] notation is helpful :
If your object is dynamic and there could be some random values in keys like number and []or any other special character, for example -
var a = { 1 : 3 };
Now if you try to access in like a.1 it will through an error, because it is expecting an string over there.
Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object.
Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.
Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.
An example where the dot notation fails
json = {
"value:":4,
'help"':2,
"hello'":32,
"data+":2,
"😎":'😴',
"a[]":[
2,
2
]
};
// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json["😎"]);
console.log(json["a[]"]);
// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.😎);
console.log(json.a[]);
The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as json.property_name
Or when you want to dynamically change the classList action for an element:
// Correct
showModal.forEach(node => {
node.addEventListener(
'click',
() => {
changeClass(findHidden, 'remove'); // Correct
},
true
);
});
//correct
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList[className]('hidden'));// Correct
}
}
// Incorrect
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList.className('hidden')); // Doesn't work
}
}
I'm giving another example to understand the usage differences btw them clearly. When using nested array and nested objects
const myArray = [
{
type: "flowers",
list: [ "a", "b", "c" ],
},
{
type: "trees",
list: [ "x", "y", "z" ],
}
];
Now if we want to access the second item from the trees list means y.
We can't use bracket notation all the time
const secondTree = myArray[1]["list"][1]; // incorrect syntex
Instead, we have to use
const secondTree = myArray[1].list[1]; // correct syntex
The dot notation and bracket notation both are used to access the object properties in JavaScript. The dot notation is mostly used as it is easier to read and comprehend. So why should we use bracket notation and what is the difference between then? well, the bracket notation [] allows us to access object properties using variables because it converts the expression inside the square brackets to a string.
const person = {
name: 'John',
age: 30
};
//dot notation
const nameDot = person.name;
console.log(nameDot);
// 'John'
const nameBracket = person['name'];
console.log(nameBracket);
// 'John'
Now, let's look at a variable example:
const person = {
name: 'John',
age: 30
};
const myName = 'name';
console.log(person[myName]);
// 'John'
Another advantage is that dot notation only contain be alphanumeric (and _ and $) so for instance, if you want to access an object like the one below (contains '-', you must use the bracket notation for that)
const person = {
'my-name' : 'John'
}
console.log(person['my-name']); // 'John'
// console.log(person.my-name); // Error
Related
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 which produces these expressions and I'm wondering which is preferable.
(Sourced from here.)
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["ダ"] (more examples).
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
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.
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"].
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
}
Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like
var x = elem["foo[]"]; // can't do elem.foo[];
This can be extended to any property containing special characters.
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
You need to use brackets if the property name 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).
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
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
Bracket notation can use variables, so it is useful in two instances where dot notation will not work:
1) When the property names are dynamically determined (when the exact names are not known until runtime).
2) When using a for..in loop to go through all the properties of an object.
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Case where [] notation is helpful :
If your object is dynamic and there could be some random values in keys like number and []or any other special character, for example -
var a = { 1 : 3 };
Now if you try to access in like a.1 it will through an error, because it is expecting an string over there.
Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object.
Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.
Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.
An example where the dot notation fails
json = {
"value:":4,
'help"':2,
"hello'":32,
"data+":2,
"😎":'😴',
"a[]":[
2,
2
]
};
// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json["😎"]);
console.log(json["a[]"]);
// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.😎);
console.log(json.a[]);
The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as json.property_name
Or when you want to dynamically change the classList action for an element:
// Correct
showModal.forEach(node => {
node.addEventListener(
'click',
() => {
changeClass(findHidden, 'remove'); // Correct
},
true
);
});
//correct
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList[className]('hidden'));// Correct
}
}
// Incorrect
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList.className('hidden')); // Doesn't work
}
}
I'm giving another example to understand the usage differences btw them clearly. When using nested array and nested objects
const myArray = [
{
type: "flowers",
list: [ "a", "b", "c" ],
},
{
type: "trees",
list: [ "x", "y", "z" ],
}
];
Now if we want to access the second item from the trees list means y.
We can't use bracket notation all the time
const secondTree = myArray[1]["list"][1]; // incorrect syntex
Instead, we have to use
const secondTree = myArray[1].list[1]; // correct syntex
The dot notation and bracket notation both are used to access the object properties in JavaScript. The dot notation is mostly used as it is easier to read and comprehend. So why should we use bracket notation and what is the difference between then? well, the bracket notation [] allows us to access object properties using variables because it converts the expression inside the square brackets to a string.
const person = {
name: 'John',
age: 30
};
//dot notation
const nameDot = person.name;
console.log(nameDot);
// 'John'
const nameBracket = person['name'];
console.log(nameBracket);
// 'John'
Now, let's look at a variable example:
const person = {
name: 'John',
age: 30
};
const myName = 'name';
console.log(person[myName]);
// 'John'
Another advantage is that dot notation only contain be alphanumeric (and _ and $) so for instance, if you want to access an object like the one below (contains '-', you must use the bracket notation for that)
const person = {
'my-name' : 'John'
}
console.log(person['my-name']); // 'John'
// console.log(person.my-name); // Error
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 which produces these expressions and I'm wondering which is preferable.
(Sourced from here.)
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["ダ"] (more examples).
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
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.
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"].
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
}
Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like
var x = elem["foo[]"]; // can't do elem.foo[];
This can be extended to any property containing special characters.
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
You need to use brackets if the property name 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).
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
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
Bracket notation can use variables, so it is useful in two instances where dot notation will not work:
1) When the property names are dynamically determined (when the exact names are not known until runtime).
2) When using a for..in loop to go through all the properties of an object.
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Case where [] notation is helpful :
If your object is dynamic and there could be some random values in keys like number and []or any other special character, for example -
var a = { 1 : 3 };
Now if you try to access in like a.1 it will through an error, because it is expecting an string over there.
Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object.
Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.
Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.
An example where the dot notation fails
json = {
"value:":4,
'help"':2,
"hello'":32,
"data+":2,
"😎":'😴',
"a[]":[
2,
2
]
};
// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json["😎"]);
console.log(json["a[]"]);
// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.😎);
console.log(json.a[]);
The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as json.property_name
Or when you want to dynamically change the classList action for an element:
// Correct
showModal.forEach(node => {
node.addEventListener(
'click',
() => {
changeClass(findHidden, 'remove'); // Correct
},
true
);
});
//correct
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList[className]('hidden'));// Correct
}
}
// Incorrect
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList.className('hidden')); // Doesn't work
}
}
I'm giving another example to understand the usage differences btw them clearly. When using nested array and nested objects
const myArray = [
{
type: "flowers",
list: [ "a", "b", "c" ],
},
{
type: "trees",
list: [ "x", "y", "z" ],
}
];
Now if we want to access the second item from the trees list means y.
We can't use bracket notation all the time
const secondTree = myArray[1]["list"][1]; // incorrect syntex
Instead, we have to use
const secondTree = myArray[1].list[1]; // correct syntex
The dot notation and bracket notation both are used to access the object properties in JavaScript. The dot notation is mostly used as it is easier to read and comprehend. So why should we use bracket notation and what is the difference between then? well, the bracket notation [] allows us to access object properties using variables because it converts the expression inside the square brackets to a string.
const person = {
name: 'John',
age: 30
};
//dot notation
const nameDot = person.name;
console.log(nameDot);
// 'John'
const nameBracket = person['name'];
console.log(nameBracket);
// 'John'
Now, let's look at a variable example:
const person = {
name: 'John',
age: 30
};
const myName = 'name';
console.log(person[myName]);
// 'John'
Another advantage is that dot notation only contain be alphanumeric (and _ and $) so for instance, if you want to access an object like the one below (contains '-', you must use the bracket notation for that)
const person = {
'my-name' : 'John'
}
console.log(person['my-name']); // 'John'
// console.log(person.my-name); // Error
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 which produces these expressions and I'm wondering which is preferable.
(Sourced from here.)
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["ダ"] (more examples).
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
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.
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"].
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
}
Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like
var x = elem["foo[]"]; // can't do elem.foo[];
This can be extended to any property containing special characters.
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
You need to use brackets if the property name 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).
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
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
Bracket notation can use variables, so it is useful in two instances where dot notation will not work:
1) When the property names are dynamically determined (when the exact names are not known until runtime).
2) When using a for..in loop to go through all the properties of an object.
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Case where [] notation is helpful :
If your object is dynamic and there could be some random values in keys like number and []or any other special character, for example -
var a = { 1 : 3 };
Now if you try to access in like a.1 it will through an error, because it is expecting an string over there.
Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object.
Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.
Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.
An example where the dot notation fails
json = {
"value:":4,
'help"':2,
"hello'":32,
"data+":2,
"😎":'😴',
"a[]":[
2,
2
]
};
// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json["😎"]);
console.log(json["a[]"]);
// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.😎);
console.log(json.a[]);
The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as json.property_name
Or when you want to dynamically change the classList action for an element:
// Correct
showModal.forEach(node => {
node.addEventListener(
'click',
() => {
changeClass(findHidden, 'remove'); // Correct
},
true
);
});
//correct
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList[className]('hidden'));// Correct
}
}
// Incorrect
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList.className('hidden')); // Doesn't work
}
}
I'm giving another example to understand the usage differences btw them clearly. When using nested array and nested objects
const myArray = [
{
type: "flowers",
list: [ "a", "b", "c" ],
},
{
type: "trees",
list: [ "x", "y", "z" ],
}
];
Now if we want to access the second item from the trees list means y.
We can't use bracket notation all the time
const secondTree = myArray[1]["list"][1]; // incorrect syntex
Instead, we have to use
const secondTree = myArray[1].list[1]; // correct syntex
The dot notation and bracket notation both are used to access the object properties in JavaScript. The dot notation is mostly used as it is easier to read and comprehend. So why should we use bracket notation and what is the difference between then? well, the bracket notation [] allows us to access object properties using variables because it converts the expression inside the square brackets to a string.
const person = {
name: 'John',
age: 30
};
//dot notation
const nameDot = person.name;
console.log(nameDot);
// 'John'
const nameBracket = person['name'];
console.log(nameBracket);
// 'John'
Now, let's look at a variable example:
const person = {
name: 'John',
age: 30
};
const myName = 'name';
console.log(person[myName]);
// 'John'
Another advantage is that dot notation only contain be alphanumeric (and _ and $) so for instance, if you want to access an object like the one below (contains '-', you must use the bracket notation for that)
const person = {
'my-name' : 'John'
}
console.log(person['my-name']); // 'John'
// console.log(person.my-name); // Error
The problem with the ECMA standard for sort of Object.keys() is known:
Object.keys() handle all keys with integer (example: 168), including integer as strings (example: "168"), as a integer. The result is, both are the same (168 === "168"), and overwrite itself.
var object = {};
object["168"] = 'x';
object[168] = 'y';
Object.keys(object); // Array [ "168" ]
object[Object.keys(object)]; // "y"
Interestingly, all keys (including pure integer keys) are returned as a string.
The ecma262 wrote about this: All keys will be handle as a integer, expect the key is a String but is not an array index.
https://tc39.es/ecma262/#sec-ordinaryownpropertykeys
That should tell us: 168 === "168". A toString() do not solve the problem.
var object = {};
object[[3].toString()] = 'z';
object[[1].toString()] = 'x';
object[[2].toString()] = 'y';
Object.keys(object);
// Array(3) [ "1", "2", "3" ]
Paradoxically, in this case, only integer apply as "enumerable" (it's ignoring array.sort(), that sort also strings with letters.).
My question about this is simple: How can i prevent the sort function in Object.keys()? I have testet the Object.defineProperties(object, 1, {value: "a", enumerable: true/false}), but that mean not realy enumerable in the case of integer or string or integer-like string. It means only should it be counted with or not. It means "counted" like omit (if it false), not "enumerabled" like ascending or descending.
A answere like that is not a good answer: Please use only letters [a-zA-Z] or leastwise a letter at the first position of keyword.
What I want: That the keys are not sorted, but output in the order in which they were entered, whether integer, string or symbol.
Disclaimer: Please solutions only in JavaScript.
Javascript Objects are unordered by their nature. If you need an ordered object-like variable I would suggest using a map.
To achieve what you're looking for with a map instead of object you'd do something like the below:
var map1 = new Map();
map1.set("123", "c");
map1.set(123, "b");
var iterator1 = map1.keys();
var myarray = [];
for (var i = 0; i < map1.size; i++) {
myarray.push(iterator1.next().value);
}
console.log(myarray);
// Array ["123", 123]
Unfortunately it's not compatible with IE and I'm not sure how else you could achieve what you need without it. A quick Google did return something about jQuery maps, though.
If you don't want to use jQuery and still need to support IE some points are below:
Is there anything stopping you using an array rather than JS object to store the data you need? This will retain the order per your requirements unlike objects. You could have an object entry in each iteration which represents the key then use a traditional foreach to obtain them as an array. I.e.
The array:
var test_array = [
{key: 123, value: 'a value here'},
{key: "123", value: 'another value here'}
];
// console.log(test_array);
Getting the keys:
var test_array_keys = [];
test_array.forEach(function(obj) { test_array_keys.push(obj['key']); } );
// console.log(test_array_keys);
Then if you needed to check whether the key exists before adding a new entry (to prevent duplicates) you could do:
function key_exists(key, array)
{
return array.indexOf(key) !== -1;
}
if(key_exists('12345', test_array_keys))
{
// won't get here, this is just for example
console.log('Key 12345 exists in array');
}
else if(key_exists('123', test_array_keys))
{
console.log('Key 123 exists in array');
}
Would that work? If not then the only other suggestion would be keeping a separate array alongside the object which tracks the keys and is updated when an entry is added or removed to/from the object.
Object Keys sorted and store in array
First Creating student Object. then sort by key in object,last keys to store in array
const student={tamil:100, english:55, sci:85,soc:57}
const sortobj =Object.fromEntries(Object.entries(student).sort())
console.log(Object.keys(sortobj))
use map instead of an object.
let map = new Map()
map.set("a", 5)
map.set("d", 6)
map.set("b", 12)
to sort the keys (for example, to update a chart data)
let newMap = new Map([...map.entries()].sort())
let keys = Array.from(newMap.keys()) // ['a','b','d']
let values = Array.from(newMap.values()) // [5,12,6]
I'm developing an iOS app and I want to access a specific value in a Dictionary using Array().
My dictionary contains an array, which contains structs.
let array = [(key: "S", value: [Thunderbolt.repoStruct(repoName: "Semiak Repo", repoURL: "https://repo.semiak.dev", icon: Optional("iconRound"))]), (key: "T", value: [Thunderbolt.repoStruct(repoName: "Thunderbolt iOS Utilities", repoURL: "https://repo.thunderbolt.semiak.dev", icon: Optional("iconRound"))])]
I'm making an UITableView with the array: the section name is the key value, the cell title is the repoStruct.repoName value, and the same with the following values.
To access repoName I'd use Array(array)[0].1[0].repoName.
The problem is that I do not know the exact location I want to access, instead, I use indexPath to know which value I need:
Array(array)[indexPath.section].indexPath.row[0].repoName
This should return me the repoName of the cell, but instead gives me the following error: Value of tuple type '(key: String, value: [repoStruct])' has no member 'indexPath'
I also tried using:
let row = indexPath.row
Array(array)[indexPath.section].row[0].repoName
but it gives me the same error: Value of tuple type '(key: String, value: [repoStruct])' has no member 'row'
I do not know why Array(array)[0].1 works and returns me the value, but Array(array)[indexPath.section].row doesn't. It is doing the same: accessing a value using the position, which is an int, such as indexPath.
How could I accomplish this?
Thanks in advance.
You are strongly discouraged from using tuples in a data source array. Replace the tuple with an extra struct
struct Section {
let name : String
let items : [Thunderbolt.repoStruct]
}
let array = [Section(name: "S", items: [Thunderbolt.repoStruct(repoName: "Semiak Repo", repoURL: "https://repo.semiak.dev", icon: Optional("iconRound"))],
Section(name: "T", items: [Thunderbolt.repoStruct(repoName: "Thunderbolt iOS Utilities", repoURL: "https://repo.thunderbolt.semiak.dev", icon: Optional("iconRound"))]]
and get an item at index path
let section = array[indexPath.section]
let item = section.items[indexPath.row]
let name = item.repoName
First of all, your array is already an array, so there's no need to say Array(array) - simply array will suffice, although generic names like this should be avoided.
I do not know why array[0].1[0] works
Let's pick this apart - your're accessing the first element in array via [0] and within that, the second element of the tuple .1, and lastly the first element of that valuearray. You could use array[0].value[0] for the same effect and make the code more readable.
but array[indexPath.section].row doesn't
That's because your array does not contain anything called row.
Use array[indexPath.section].value[indexPath.row].repoName instead.
Please try this code.
let dictData = arr[indexpath.section] //Element of section
let value = dictData["value"] //Value added in value in The element
let name = value[indexpath.row].reponame //Gives you name