DEV Community

Saran Chakravarthi
Saran Chakravarthi

Posted on • Edited on

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",
  },
};

Enter fullscreen mode Exit fullscreen mode

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' }

Enter fullscreen mode Exit fullscreen mode

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"); 

Enter fullscreen mode Exit fullscreen mode

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");

Enter fullscreen mode Exit fullscreen mode

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!

Top comments (2)

Collapse
 
lapalb profile image
Ashish Jha

As a general rule of Thumbs, Alwayys use dot notation excepts following two cases:

  1. To Access something like animalsList[animal], where key is variable.
  2. When key contains dash. person.birth-year will give an error, hence we will have to use person['birth-year']
Collapse
 
saran_chakravarthi profile image
Saran Chakravarthi

Thanks for pointing it out, Ashish.