Learn JavaScript: Objects


#1

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.


#2

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'

console.log(obj[key])

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

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

#3

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


#4

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