This content originally appeared on DEV Community and was authored by Saran Chakravarthi
Hello Devs, in this article, I will walk you through the differences between using dot notation and bracket notation in JavaScript objects.
Consider the following object.
let animalsList = {
cow:{
legs: 4,
sound: "moo",
},
cat:{
legs: 4,
sound: "meow",
},
};
We can use both dot and bracket notation to access the properties. Make sure that you enclose the key within quotes, when you use bracket notation.
console.log(animalsList.cat); //{ legs: 4, sound: 'meow' }
console.log(animalsList["cat"]); //{ legs: 4, sound: 'meow' }
As you can see, dot notation has better readability, it is an advantage of using dot notation.
"So, if we can use both dot notation and bracket notation to access object properties, and dot notation has better readability, why do we even have bracket notation?", you might ask.
Let's say we have a function, and the key which we have to access is passed to the function as an argument.
function myFun(animal){
console.log(animalsList.animal);
}
myFun("cow");
The above code will print undefined
.
When we use dot notation, JavaScript searches for the key with the exact name we used after the dot( animal, in our case). Since the animalsList doesn't have a property called "animal", undefined is printed.
Let's try bracket notation instead of dot notation.
function myFun(animal){
console.log(animalsList[animal]);
}
myFun("cow");
The above code will work fine and print { legs: 4, sound: 'moo' }
, as "animal" will be replaced with the respective argument which was passed during function call.
To summarize, use bracket notation when you want to access property using variable, otherwise stick with dot notation.
I hope this article helped you. Happy coding!
This content originally appeared on DEV Community and was authored by Saran Chakravarthi
Saran Chakravarthi | Sciencx (2021-07-13T20:38:09+00:00) Bracket notation Vs dot notation in JavaScript objects. Retrieved from https://www.scien.cx/2021/07/13/bracket-notation-vs-dot-notation-in-javascript-objects/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.