Bracket Notation

Bracket Notation

  • Bracket notation is another way to to access a key’s value is by using bracket notation, [ ]

  • To use bracket notation to access an object’s property, we pass in the property name (key) as a string

    superHero['secret identity']`

  • We must use bracket notation when accessing keys that have numbers, spaces, or special characters in them

  • Remember, object keys are always strings


Example

const superHero = {
  'secret identity': 'Peter Parker',
  name: 'Spiderman',
  powers: ['super strength', 'hyper awareness', 'agility', 'genius intellect'],
  age: 17
}

console.log(superHero["secret identity"])
console.log(superHero["name"])

JS Bin on jsbin.com


Using variables to access properties

  • Bracket notation also allows us to use a variable inside the brackets to select the keys of an object

Example

const superHero = {
  'secret identity': 'Peter Parker',
  name: 'Spiderman',
  powers: ['super strength', 'hyper awareness', 'agility', 'genius intellect'],
  age: 17
}

const attribute = "name"

// use the 'attribute' variable to access a property in superHero
const attributeValue = superHero[attribute]


console.log(superHero[attribute])

// This is the result of trying the same thing using dot notation
console.log(superHero.attribute) // undefined

JS Bin on jsbin.com