⊗jsPmObPAM 92 of 504 menu

Error accessing object property in JavaScript

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']);
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline