Bracket notation Vs dot notation in JavaScript objects

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. Want to connect with me? my DM is open on dev.to, you can connect with me on twitter.

Happy coding!

21