DEV Community

Samantha Ming
Samantha Ming

Posted on • Updated on • Originally published at samanthaming.com

Dot notation vs Bracket notation

Code Tidbit by SamanthaMing.com

Both notations can access object properties. But the question is often which one should I use 🤔. Wonder no more, just follow Airbnb's style guide. Always use Dot. And when you want to access object property with a variable, use Bracket 👍

// Dot notation vs Bracket notation

const variable = 'cookie';

const snack = {
  cookie: '🍪'
};

// ✅ Dot: access property
snack.cookie;

// ✅ Bracket: access property with variable
snack[variable];

Accessing Object Properties

There are 2 ways to access object properties. Dot and Bracket.

const obj = {
  name: 'value'
};

// Dot Notation
obj.name; // 'value'

// Bracket Notation
obj['name']; // 'value'

Dot Notation for the win

I remember when I was first learning this. Understanding the 2 different ways was simple. Nothing too complicated. But my concern was never about the different notations. My biggest dilemma was, WHICH SHOULD I USE?? 🤯

If you were like me! Here's the breakdown. They both do the same. So here is the simple rule. By default, just use the Dot notation.

✅ Dot Notation 🏆

  • It's a lot easier to read
  • It's way faster to type.

Dot Notation's Limitation

With any rule, there are always exceptions 😂. So let's look at some of the limitations.

a. Issue working with Identifiers
b. Issue working with Variables

a. Working with JavaScript Identifiers

One of the major limits of using the Dot notations is that it only works with valid identifiers. First, let' me define what is an identifier

An identifier is a sequence of characters in the code that identifies a variable, function, or property.

MDN web docs

The identifier has the following rules:

  • case sensitive
  • can contain Unicode letters
  • $, -, are allowed
  • Digits (0-9) are okay BUT may not start with a digit

So let's sample some of these examples and see what happens when we use the Dot notation.

const obj = {
  123: 'digit',
  123name: 'start with digit',
  name123: 'does not start with digit',
  $name: '$ sign',
  name-123: 'hyphen',
  NAME: 'upper case',
  name: 'lower case'
};

Note:

You may notice some property names I had to include quotes. Example: 123name. I had to do that otherwise the object would be considered invalid and it would throw a Syntax Error.

Dot Notation

obj.123;      // ❌ SyntaxError
obj.123name;  // ❌ SyntaxError
obj.name123;  // ✅ 'does not start with digit'
obj.$name;    // ✅  '$ sign'

obj.name-123;  // ❌ SyntaxError
obj.'name-123';// ❌ SyntaxError

obj.NAME; // ✅ 'upper case'
obj.name; // ✅ 'lower case'

See how I tried to be clever and use quotes in the obj.'name-123' example. Well, don't, cause it still won't work 😂.

Bracket Notation

But none of this is a problem for the Bracket Notation.

obj['123'];     // ✅ 'digit'
obj['123name']; // ✅ 'start with digit'
obj['name123']; // ✅ 'does not start with digit'
obj['$name'];   // ✅ '$ sign'

obj['name-123']; // ✅ 'does not start with digit'

obj['NAME']; // ✅ 'upper case'
obj['name']; // ✅ 'lower case'

Verdict

If you think you have an invalid JavaScript identifier as your property key, use the Bracket Notation 👍

b. Accessing Property with Variables

Another limitation of the Dot notation is working with variables. You definitely should use the Bracket Notation. Note! When you're referencing a variable in the Bracket Notation, you need to skip the quote. That's kinda how you know you're dealing with a variable instead of accessing the property key.

const variable = 'name';

const obj = {
  name: 'value'
};

// Bracket Notation
obj[variable]; // ✅ 'value'

// Dot Notation
obj.variable; // undefined

Undefined Property

One very important thing I want to point out. You will notice that if I try to use the Dot notation on the variable, it returns undefined. This is because when you try to access a property that doesn't exist, it will return undefined.

const emptyObj = {};

obj.name; // undefined
obj['name']; // undefined

So here's the watch-out part. Let's return to our variable object example previously. If you used the Dot notation, it will just assume you're trying to access the property with a valid JavaScript identifier. Because it's returning something, you might think everything is working fine. Under the hood, yes it is. But if your intention is to use the variable, it might throw you off. This definitely can be a source of a debugging headache. So watch out for that!!

const variable = 'name';

const obj = {
  name: 'value',
  variable: '👻'
};

// Bracket Notation
obj[variable]; // ✅ 'value'

// Dot Notation
obj.variable; // '👻'

Verdict

Never use the Dot Notation when using a Variable

Conclusion

Knowing the limitations of Dot Notation, let's update our rule.

Use the Dot Notation. But if you're dealing with invalid identifier or variables, use the Bracket notation.


Community Input

  • @Marcello Nicoletti: [Another benefits of the Dot notation] It also looks like object usage in other C-like languages. It will be easier to read and write for people coming from C, C#, and Java.

Resources


Thanks for reading ❤
Say Hello! Instagram | Twitter | Facebook | Medium | Blog

Top comments (15)

Collapse
 
clovis1122 profile image
José Clovis Ramírez de la Rosa • Edited

Great post, Samantha!

Another case where I would personally use bracket notation is when the property name is odd - that alerts the reader that the properties in the object are non-standard!

user.firstName;      // camelCase notation as usual.
user['first_name'];  // underscore notation, using brackets to remark that the name is different!
Collapse
 
samanthaming profile image
Samantha Ming

Good example! Thanks for sharing that 👍

Collapse
 
marcellonicoletti profile image
Marcello Nicoletti

Another place bracket notation is useful is when you use a minifier. Minifiers can be configured to replace dot notation identifiers. This isn't an issue for most cases, but it is when you reference a DOM element's attributes. The value in the HTML will not get changed by minification so your references shouldn't either. Minifiers won't change strings so bracket notation using a string is how you can ensure DOM references work after minification.

Collapse
 
sameerchandra profile image
Sameer Chandra Nimushakavi

So, dot is preferred just for ease of use and nothing else?

Collapse
 
marcellonicoletti profile image
Marcello Nicoletti • Edited

It also looks like object usage in other C-like languages. It will be easier to read and write for people coming from C, C#, and Java.

EDIT: I guess that's still ease of use, but in a different way than mentioned in the post. As far as I know there is no time difference when the code is actually running so there is only really differences in ease.

Collapse
 
samanthaming profile image
Samantha Ming

Woo! Definitely an advantage 👍 will add that to my notes 😊

Collapse
 
samanthaming profile image
Samantha Ming

Yup! But isn’t that enough of a selling point 😝

Collapse
 
baso53 profile image
Sebastijan Grabar

While I agree with you on the part which one you should use, I don't like how you said 3 times in the article - "Always use the dot notation". It wasn't explained why, just that you should "follow a popular style guide". That could lead to a wrong path down the road, doing something just because it's popular.

Collapse
 
samanthaming profile image
Samantha Ming

Fair point! I definitely could have dive more into it. Thanks for the feedback 👍

Collapse
 
laurieontech profile image
Laurie

Such a great idea for a post! I remember how much I struggled with guessing which one to use when I first started. Now it seems so natural, but I have no idea when it transitioned.

Collapse
 
samanthaming profile image
Samantha Ming

Me too!!! Getting the concept was the easy part. But the confusion is when to use which. I remember getting very frustrated with that 😅. Glad this article was helpful! And I’m always taking content suggestion, if there any topics you want me to cover, just let me know 😊👍

Collapse
 
christopherkade profile image
Christopher Kade

Loving these frequent code snippets Samantha ! 😄

Collapse
 
samanthaming profile image
Samantha Ming

Yay! Glad to hear that! It also helps sharpen my JS skills, so win win 😊 if there are topics you want me to cover, just let me know! 👍

Collapse
 
fellipegpbotelho profile image
Fellipe Geraldo Pereira Botelho

Great post Samantha!

Collapse
 
samanthaming profile image
Samantha Ming

Thanks! Glad you find it helpful 😃👍