Difference between dot(.) notation and square brackets ([]) notation used in Javascript

Taniyasharma57
2 min readSep 4, 2022

In JavaScript we can access the properties of object using dot notation(person.first_name) and bracket notation(person[first_name]). But what’s the difference between these two notations and when to use which one?

Let's see some of the important points of dot and bracket notations

To access javascript object properties using dot notation, the

  • Property identifiers can only be alphanumeric (and _ and $)
  • Property identifiers cannot start with a number.
  • Property identifiers cannot contain variables.
  • Valid Identifier (contain Unicode letters, $, _, and digits (0–9), but may not start with a digit)
  • do not start with a digit or hyphen
  • no spaces
  • do not include special characters except $ and _ (underscore)
  • obj.prop_1, obj.prop$ is correct
  • obj.1prop, obj.prop name is incorrect

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’

To access javascript object properties using bracket notation, the key should be

  • Property identifiers have to be a String or a variable that references a String.
  • we can use variables, spaces, and Strings that start with numbers
  • it can be an expression
  • obj[“1prop”], obj[“prop name”] is correct

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’

We can also access the value stored at that particular key by making a variable and then using the square brackets notation. This property of square brackets is known as a dynamic property.

Let’s understand through an example,

var student={rollno:1, name:”Aman”, ’last-name’:”Sharma”,subject:’Js’};

var key=’last-name’;

student[key];✅

Sharma

student. key; ❌the error will be generated because key = ‘last-name’ which contains a special character that cannot be used in dot notation therefore we have to use square brackets.

Thank you for reading this far. This is a brief introduction to the Difference between accessing object properties using dot and bracket notation in JS. If you find this article useful clap and share this article. Someone could find it useful too. See you in my next article!

--

--