When to use [ ] and .(dot) when dealing with objects?

Modified on Thu, 18 Jul at 9:13 AM

When working with JavaScript objects, you'll often find yourself accessing and manipulating their properties. Two common ways to do this are using dot notation (.) and square bracket notation [ ]. But when should you use each one? 


The Dot Notation(.)


Let's start with the most common and straightforward method: dot notation. 

You've probably seen this countless times in JavaScript code:


let person = { name: "John", age: 30 };

console.log(person.name); // Output: John


Dot notation is clean, concise, and easy to read. It's the go-to choice when you're dealing with properties that are simple strings and valid identifiers. 


But what exactly is a valid identifier?

  • It must start with a letter, underscore (_), or dollar sign ($)
  • Subsequent characters can be letters, numbers, underscores, or dollar signs
  • It can't be a reserved JavaScript keyword


In essence, if your property name could be a valid variable name, you can use dot notation.


Square Bracket Notation( [] )


While dot notation is great for simplicity, square bracket notation offers more flexibility. Here's when you'll want to reach for those square brackets:


1. Properties with Special Characters


If your property name contains spaces, starts with a number, or includes special characters, dot notation won't work. Square brackets to the rescue!


let person = { "full name": "John Doe", "2nd address": "123 Main St" };

console.log(person["full name"]); // Output: John Doe

console.log(person["2nd address"]); // Output: 123 Main St


2. Dynamic Property Access


One of the most powerful features of square bracket notation is the ability to use variables or expressions to access properties dynamically:


let person = { name: "John", age: 30 };

let property = "name";

console.log(person[property]); // Output: John


// You can even use expressions

console.log(person["na" + "me"]); // Output: John


Making the Choice: Dot or Brackets?


So, when should you use each notation? Here's a quick guide:

  • Use dot notation when:
    • You know the exact property name at coding time
    • The property name is a valid identifier
    • You want the most readable and concise code
  • Use square bracket notation when:
    • The property name includes special characters or spaces
    • You need to access properties dynamically
    • You're working with numeric properties


Remember, while you can use square bracket notation in most cases where dot notation works, it's generally recommended to use dot notation when possible for better readability.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article