Strings As Keys
Accessing a property using dot notation (e.g., desk.height) is excellent when the name of the property is static—meaning you know exactly what the key is while writing the code.
But what if the key is dynamic? For example, what if you need to look up a property based on a string provided by the user at runtime?
Bracket Notation
When you need to access a property dynamically, use bracket notation instead of dot notation.
const desk = {
wood: "maple",
width: 100,
};
// Static lookup
console.log(desk.wood); // Output: "maple"
// String lookup
console.log(desk["wood"]); // Output: "maple"
// Dynamic lookup via a variable
const key = "wood";
console.log(desk[key]); // Output: "maple"
Practical Example
Bracket notation is essential when writing generalized lookup functions where the key is passed as an argument.
const userAges = {
Lane: 28,
Breanna: 26,
John: 30
};
function getAge(dataObj, personName) {
// We CANNOT use dataObj.personName here,
// because it would literally look for a key named "personName"!
return dataObj[personName];
}
console.log(getAge(userAges, "Breanna")); // Output: 26