Error accessing element by key in JavaScript

When referring to an object element through square brackets, key names must be quoted, but variable names must not. Misunderstanding this can often lead to errors. So let's discuss the rules of accessing again.

In the following code, we get an element with the key 'key' from the object:

console.log(obj['key']);

And in the following code, we get an element with a key from the object, the name of which is stored in the variable key:

console.log(obj[key]);

Fix the error in the following code:

let obj = {x: 1, y: 2, z: 3}; console.log(obj[x]);

Fix the error in the following code:

let obj = {x: 1, y: 2, z: 3}; let key = 'x'; console.log(obj['key']);
enru