Skip to main content

Command Palette

Search for a command to run...

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

Updated
โ€ข2 min readโ€ขView as Markdown
DOT NOTATION OR BRACKET NOTATION ๐Ÿค”๐Ÿค”
P

A blockchain and tech enthusiast, passionate about bringing in more women and African youths from rural areas into the tech ecosystem.

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

F

Good points mentioned ๐Ÿ‘

1
J
Jebitok5y ago

Awesome topic

1
K

Lovely. Educational

1
J

Nicely and well written! Thanks Preshy for sharing your thoughts.

1
P

Thanks for the support Joshua

Y

Nicely written and well explained.

One suggestion: Instead of using bold text to separate parts of your article you may use different headings (##, ###) with markdown.

2
P

Thank you so much Yuvraj Singh Jadon

1