8 of 17 menu

The Error of Getting an Object Element in JavaScript

Let's say we have some object:

let obj = { a: 1, b: 2, c: 3, d: 4, e: 5, };

Let's say we want to get an element from this object by a certain key. Let the name of this key be entered by the user into an input:

console.log(input.value);

Some beginner programmers make the following mistake: they iterate over the object in a loop, comparing the keys one by one with the input value, like this:

for (let key in obj) { if (key === input.value) { let elem = obj[key]; console.log(elem); // the desired value break; } }

However, in this task, the loop is completely unnecessary. After all, we can simply get our value by key, like this:

let elem = obj[input.value];

If necessary, you can add a check for the presence of such a key in the object:

if (obj[input.value] !== undefined) { let elem = obj[input.value]; console.log(elem); } else { console.log('no such key in the object'); }
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