Bracket notation [ ]

In javascript, there are many ways to access object property

  • Dot notation speaker.name
  • Bracket notation speaker['name']
  • Object destructuring const { name } = speaker

Today we look at bracket notation and its different use cases.

Common use of bracket notation

With bracket notation, we can use directly property name or store it in a variable. Store property name in a variable is useful when the property name is not a valid identifier.

let fullName = 'full Name';

const speaker = {
  firstName: 'Berenger',
  lastName: 'MPAMY',
  'full Name': 'Berenger MPAMY',
};

console.log(speaker['firstName']); // => Berenger
console.log(speaker[fullName]); // => Berenger MPAMY

Object iteration with for...in

for..in is built for iterating object properties and it syntax is very simple

let arr = [];
const speaker = {
  firstName: 'Berenger',
  lastName: 'MPAMY',
};
for (let property in speaker) {
  arr.push(speaker[property]);
}
console.log(arr); //=> ['Berenger', 'MPAMY']