Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about Dot Vs Bracket Notation In JavaScript.
Table of Contents
Dot Vs Bracket Notation In JavaScript
In JavaScript, dot notation and bracket notation are two ways to access properties of an object.
Dot notation is used when the property name is known and is a valid identifier (i.e. a string containing only letters, numbers, and underscores, and not starting with a number). For example:
Code For Dot Notation In JavaScript
let obj = {
name: "John",
age: 30
};
console.log(obj.name);
console.log(obj.age);
Output
"John"
30
Bracket notation is used when the property name is not known until runtime, or when the property name is not a valid identifier. In this case, the property name is passed as a string inside the brackets. For example:
Code For Bracket Notation In JavaScript
let obj = {
name: "John",
age: 30
};
let prop = "name";
console.log(obj[prop]);
prop = "age";
console.log(obj[prop]);
Output
"John"
30
You can also use bracket notation to access properties with spaces or other characters that are not valid in variable names. For example:
let obj = {
"first name": "John",
"last name": "Doe"
};
console.log(obj["first name"]);
console.log(obj["last name"]);
Output
"John"
"Doe"
Conclusion
So to sum up, the dot notation is used to access properties that are known at design time and are valid identifiers. While the bracket notation is used to access properties that are not known until runtime or when the property name is not a valid identifier.
Also, you can use the bracket notation to access properties dynamically.
It’s up to you to decide which notation to use depending on your needs.
If you liked this post, then please share this with your friends and make sure to bookmark this website for more awesome content.