DOT NOTATION OR BRACKET NOTATION ๐Ÿค”๐Ÿค”

DOT NOTATION OR BRACKET NOTATION ๐Ÿค”๐Ÿค”

ยท

2 min read

In the course of my learning, I got to know about the two ways to access object properties - Dot Notation and Bracket Notation. I'll be breaking down the pros and cons of both methods.

Dot notation is way easier to read and faster to type

const object = {
  name: 'Cat',
  limps: 4
}

// Dot notation
object.name // 'Cat'
object.limps // 4

//Bracket notation
object['name'] // 'Cat'
object['limps'] // 4

See why I said dot notation is easier to type. By default, I use dot notation except in some special cases which you'd get to see below.

Only valid identifiers can be accessed with dot notation

According to MDN Web Docs glossary:

An identifier is a sequence of characters in the code that identifies a variable, function, or property. In JavaScript, identifiers are case-sensitive and can contain Unicode letters, $, _, and digits (0-9), but may not start with a digit.

const object = {
  name: 'Cat',
  limps: 4,
  123: 'numbers',
  9lives: 'starts with numbers',
  $live: 'starts with $'
}

// Dot notation
object.name // 'Cat'
object.limps // 4
object.123 // syntax error
object.9lives // syntax error
object.$live //  'starts with $'

//Bracket notation
object['name'] // 'Cat'
object['limps'] // 4
object['123'] // 'numbers'
object['9lives'] // 'starts with numbers'
object['$live'] //  'starts with $'

The code snippet above shows identifiers that can be accessed using bracket notation but can't be accessed with dot notation. If you're using an invalid identifier for an object property, be sure to use the bracket notation.

Accessing object properties using variables

const object = {
  name: 'Cat',
  limps: 4
}

//assigning a property to a variable
const pet = 'name'

// Dot notation
object.pet // undefined

//Bracket notation
object[pet] // 'Cat'

When we assign an object property to a variable, we can only access that property using the variable by using the bracket notation. The dot notation would return undefined. Remember to skip the quotes.

In summary

Use the dot notation unless when accessing properties with invalid identifiers or using a variable.

Don't forget to comment below and show your support by liking this article and follow me on Twitter

PS: this is my first article on HashNode