Accessing object properties with bracket notation
JavaScriptAll snippets in this category →
Posted on We can access object properties using dot notation if we can hardcode the property name. If the name is dynamic, such as when it is stored in another variable, that no longer works.
We can use bracket notation in those situations instead.
const storage = {
candy: 5,
chocolate: 6
}
// We can access properties directly by name using dot-notation. We can also
// access them by writing their name as a string in square brackets:
storage.candy // ⇒ 5
storage["candy"] // ⇒ 5
// If we don’t know the name of the property because it only exists in a
// variable, we _have_ to use bracket notation:
const lookUp = "chocolate"
storage.lookUp // ⇒ undefined (looks for missing property "lookUp")
storage[lookUp] // ⇒ 6
const storage = {
candy: 5,
chocolate: 6
}
// We can access properties directly by name using dot-notation. We can also
// access them by writing their name as a string in square brackets:
storage.candy // ⇒ 5
storage["candy"] // ⇒ 5
// If we don’t know the name of the property because it only exists in a
// variable, we _have_ to use bracket notation:
const lookUp = "chocolate"
storage.lookUp // ⇒ undefined (looks for missing property "lookUp")
storage[lookUp] // ⇒ 6
const storage = {
candy: 5,
chocolate: 6
}
// We can access properties directly by name using dot-notation. We can also
// access them by writing their name as a string in square brackets:
storage.candy // ⇒ 5
storage["candy"] // ⇒ 5
// If we don’t know the name of the property because it only exists in a
// variable, we _have_ to use bracket notation:
const lookUp = "chocolate"
storage.lookUp // ⇒ undefined (looks for missing property "lookUp")
storage[lookUp] // ⇒ 6
const storage = {
candy: 5,
chocolate: 6
}
// We can access properties directly by name using dot-notation. We can also
// access them by writing their name as a string in square brackets:
storage.candy // ⇒ 5
storage["candy"] // ⇒ 5
// If we don’t know the name of the property because it only exists in a
// variable, we _have_ to use bracket notation:
const lookUp = "chocolate"
storage.lookUp // ⇒ undefined (looks for missing property "lookUp")
storage[lookUp] // ⇒ 6