Difference between Dot notation & Bracket notation in JavaScript Objects

Difference between Dot notation & Bracket notation in JavaScript Objects

Photo by Andrew Neel on Unsplash

There are two ways to retrieve data from Objects in JavaScript , Dot ‘ . ’ and Bracket ‘[]’ notation. The main difference between Dot notation and bracket notation is that the bracket notation allows us to access object properties using variable.

const User = {
  firstName: 'Sham',
  lastName: 'Gurav',
  age: 25,
  role: 'Frontend Developer',
  skills: ['HTML' , 'CSS' , 'JavaScript']
}

Both User.firstName and User['firstName'] will access the firstName property on User Object but not necessarily the same property. The difference is in how the property name is interpreted.

When using Dot notation the word after the dot is the literal name of the property. When using square brackets notation, the expression between the brackets is evaluated to get the property name.

console.log(User.firstName)             // 'Sham'
console.log(User['firstName'])          // 'Sham'
console.log(User['first' + 'Name'])    // 'Sham'

The Dot notation is more readable and it is shorter but it comes with some limitation. You have to use square Bracket notation when -

  1. The property name is number
const obj = {
  123: 'groupA',
  firstName: 'John'
  }
console.log(obj.123);       // Syntax Error ❌
console.log(obj['123']);    // 'groupA' ✅
  1. The property name has special character. Special characters like space , emojis , etc.
const obj = {
  'Rocket 🚀': 'launch',
  }
console.log(obj.Rocket 🚀);        // Syntax Error ❌
console.log(obj['Rocket 🚀']);     //'launch' ✅
  1. The property name is assigned to a variable and you want to access the property value by this variable. It is very useful in scenarios where you want to take input from User OR the exact property names are not known till runtime.
const User = {
  firstName: 'Sham',
  lastName: 'Gurav',
  age: 25,
  role: 'Frontend Developer'
  }

var userInput = 'firstName';
console.log(User.userInput);       // undefined ❌
console.log(User[userInput]);      // 'Sham' ✅

Dot notation is always preferred . If you are using smart IDE then it will show as undefined or it will throw error for invalid properties of objects. Use Bracket notation only when property name starts with number or includes any special characters or property name is unknown till runtime.

Did you find this article valuable?

Support Sham Gurav by becoming a sponsor. Any amount is appreciated!