DEV Community

Cover image for Use Square Bracket Notation for headache-free coding
Yanger Rai
Yanger Rai

Posted on

Use Square Bracket Notation for headache-free coding

Ok! So this happened! I failed an interview because I overlooked the basic!

There are two ways to access property values of an object in javascript:

  1. Dot notation ( user.name )
  2. Square Bracket notation ( user["name"])

And most of the time, property names are known and simple and dot notation comes naturally to many of us.
South Park character

But there is a catch. Read on!


Objects

TL;TR -

Square bracket notation saved you from breaking your head compared to dot notation.
When you defined a key into a variable and wants to add it as new property into an object, it will only work if square bracket notation is used.

let user = {
  name: "John",
  age: 30
};
let key = "gender";
user.key = "male";
alert( user.gender ) // undefined
user[key] = "male";
alert( user.gender ) // male

Use dot notation:
When an object is already defined and you just want to read the property provided all property are single word.
Single word: "name"

Avoid dot notation:
When an object is already defined and you just want to read the property but few or all property are multiword.
multiword: "first name"

let user = {
  name: "John",
  age: 30,
  "likes birds": true  // multiword property name must be  quoted
};

user.likes birds = true // this would give a syntax error
Enter fullscreen mode Exit fullscreen mode

Use square bracket notation:
I mean in all case (at least from what I know, feel free to comment )

few examples: Works for all operators like charm

let user = {};

// set
user["likes birds"] = true;

// get
alert(user["likes birds"]); // true

// delete
delete user["likes birds"];
Enter fullscreen mode Exit fullscreen mode

Avoid square bracket notation:
adult male swinging
Guess we'll never know....


Read more about Objects

Top comments (2)

Collapse
 
mrwormhole profile image
Talha Altınel

nice nuance to point out, but it comes down to the developer choice, there is no right or wrong, since ES spec defines JSON objects as a class and a map at the same time. Generally it is considered bad practice to put blank spaces in your keys. If you need a map, use it is a map, if you need a class, use it as a class.

Collapse
 
yangerrai profile image
Yanger Rai

Indeed. No right or wrong way but preferences