Learn JavaScript: Objects

There was no category about JavaScript objects, so I found the closest one to it.

When accessing a object using bracket notation, why do you have to make the key value into a string? It seems useless and don’t see the point in using that. Dot notation seems like the easiest way.

1 Like

Because in JavaScript, all keys are strings, even if they are numeric.

obj = {
    1: 'one',
    2: 'two',
    3: 42

for (x in obj) {
    console.log(x, typeof(x));
1 string
2 string
3 string

When accessing the value by subscript,

console.log(obj['3'])    //  42

Consider if we try accessing without quotes on the key…

console.log(obj[3]))    // 42

JavaScript coerced the number to a string, in this case, but what if the key has word characters?

 obj['key'] = 'value'


Uncaught ReferenceError: key is not defined
at :1:18

console.log(obj['key'])    // value

Lol I just saw the next exercise which answered my question. Thanks again! I gotta finish a segment before asking questions like this…


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.