In JavaScript, we know that objects are often made up of properties/keys and values, and we may use the dot notation to add, edit, or access some value(s). As an example:
let lion = {
category: "carnivore"
};
console.log(lion); // {category: "carnivore"}
lion.baby = "cub";
console.log((lion.category); // carnivore
console.log(lion); // {category: "carnivore", baby: "cub"}
We also have the option of using square bracket notation, which is utilized when we need dynamic object keys.
What do we mean by dynamic object keys?
These are keys that might not follow the standard naming convention of properties/keys in an object. The standard naming convention only permits camelCase and snake_case, but by using square bracket notation we can solve this problem.
For example, suppose we name our key with a dash in between words, for example (lion-baby):
let lion = {
'lion-baby' : "cub"
};
// dot notation
console.log(lion.lion-baby); // error: ReferenceError: baby is not defined
// bracket notation
console.log(lion['lion-baby']); // "cub";
You can see the difference between the dot notation and the bracket notation. Let's see other examples:
let category = 'carnivore';
let lion = {
'lion-baby' : "cub",
[category] : true,
};
console.log(lion); // { lion-baby: "cub" , carnivore: true}
You can also perform more complex operations by using conditions within the square bracket, like this:
const number = 5;
const gavebirth = true;
let animal = {
name: 'lion',
age: 6,
[gavebirth && 'babies']: number
};
console.log(animal); // { name: "lion" , age: 6 , babies: 5 }};
You can read more about this here.
Post a Comment