When accessing an object property, the name of that property cannot be stored in a variable. Let's see why. Suppose we have such an object:
let obj = {a: 1, b: 2, c: 3};
Let the variable store the name of the property whose value we want to get:
let key = 'a';
Let's try to access the object property using this variable:
console.log(obj.key); // undefined
The above code will not work because
we are actually looking for the property
named 'key'
, not the property
whose name is stored in the variable
key
. That is, in fact, our code
is equivalent to the following:
console.log(obj['key']);
The only way to access an element by key from a variable is to write this variable in square brackets:
console.log(obj[key]);
Fix the error in the following code:
let obj = {x: 1, y: 2, z: 3};
let prop = 'x';
console.log(obj.prop);
Fix the error in the following code:
let obj = {x: 1, y: 2, z: 3};
let prop = 'x';
console.log(obj['prop']);