➕bracket notation []
`obj[prop]` syntax.
JS ⟩ statement ⟩ expression ⟩ operator ⟩ left-hand side ⟩ property accessor ⟩ bracket notation
(property access expression) (🌟 chaining rules | table of operators )
use obj [ prop ] to evaluate an object property / array element.
// ⭐️ bracket notation
obj [ prop ] // obj: non-nullish, prop: string | symbol (any other value coerced to string)🈯 synonyms: "computed property access"
the [prop] part of bracket notation []:
is evaluated and converted to a string❗
✅element index is accessed throught bracket notation.
bracket notation ⟩
is a dynamic way to access associated array.
uses brackets [] punctuator.
replit:bracket notation
// object
let obj = { name: 'Joe' };
// ⭐️ bracket notaton
// -------------------------------------------------------------------
// • syntax: `obj [ prop ]`
// • obj : expression (❗ value of null/undefined raises TypeError)
// • prop: expression (❗ evaluated and "converted" to string)
// -------------------------------------------------------------------
obj[''] = 'joe'; // ✅ "empty string" is OK
obj[' '] = 'OK'; // ✅ "space" is OK
obj[true] = true; // ✅ boolean is OK
const key = "name"; // variable
const getKey = () => "name"; // function
// ⭐️ `prop` can be any expression.
obj["name"], // 'Joe' (prop: string literal)
obj[key], // 'Joe' (prop: variable)
obj[getKey()], // 'Joe' (prop: function return value)Last updated
Was this helpful?