Accessing Properties of an Object in Javascript

Photo by Mary B on Unsplash

Accessing Properties of an Object in Javascript

You like that car right? I do too(smiles)... Okay now be serious.

Accessing Properties of an Object in Javascript

Let us take a look at the different ways of accessing object properties in Javascript.

There are two basic ways of accessing object properties in Javascript,

  • The dot notation
  • The bracket notation

So when could you use bracket notation? Square brackets allow you to use property names that are not valid identifiers and don't work with dot notation, for example when they have spaces in them or start with a number. Also, bracket notation allows you to use property names that are variables. Examples of both are below

The dot notation

//dot notation
let Toyota = {
 model: "Tacoma",
 year: 2021,
 color: "red",
 transmission: "front-wheel drive",
};

console.log(Toyota.transmission);

The bracket notation


let element = {
  "box sizing": "border sizing"  //property with space in them or more than one word
};

console.log(element["box sizing"])
let Toyota = {
  car1: 3,
  car2: 7,
  car3: 9,
  car4: 14,
  car5: 23,
  car6: 28,
};

for(let i = 1; i < 7; i++;){
  let prop = 'car' + i;  //with variable property name
  console.log(Toyota[prop]);
}

I hope you can now understand the difference between the dot notation and the bracket notation. Feel free to leave your comment or ask your question in the comment section. Thank you.