Question

var thing = {"gabba gabba": "hey", "5": 10};
show(thing["5"]);
thing["5"] = 20;
show(thing[2 + 3]); // = 20
show(thing[2]); // = undefined
show(thing[3]); // = undefined

I do not understand why show(thing[2+3]) = 20 and the other two below it return undefined. What do the 2 and 3 refer to? Could someone help me out with this? Thanks.

Was it helpful?

Solution

The expression thing[2] means to find a property on the object named thing with the name "2". Since property names are strings, the number 2 is automatically converted to the string "2". Since that object has no such property, the result is undefined.

The expression thing[2+3] means to first evaluate 2+3 which is 5. Then 5 is converted from a number to a string "5", and then find the property on thing with that name. Thus the result is 20.

OTHER TIPS

I do not understand why show(thing[2+3]) = 20 and the other two below it return undefined.

thing[2+3] evaluates to thing[5] (==20), but properties with the names "2" or "3" don't exist on your object - and therefore yield undefined when being accessed.

What does the 2 and 3 refer to?

They're plain number literals.

The point is that thig is not an Array, it is an Object (key : value pairs). If you like to get "hey" youd need to do:

show(thing["gabba gabba"]); // = "hey"

And because there is an entry with key "5", 2 + 5 works:

show(thing["5"]);   // = 10
show(thing[2 + 3]); // = 10

You have given the 5th term of "thing" the value of 20

thing["5"] = 20;

Javascript is clever enough to understand that when you type

thing[2 + 3]

What you really want is

thing[5]

What you're not doing is

thing[3] + thing [2]

However, thing[2] and thing[3] have no value, hence, they return as undefined. You'd need to give them a value, like you did before when you gave thing[5] a value of 20.

That's the way JavaScript Objects work. You can consider them as a kind of HashMap with keys and values.

In your example you've got a HasMap object called thing which has only 2 pair of key-values. "gabba gabba" is the key for the first one with hey as its value, the second pair has "5" as its key and 10 is the value. To make it more comprehensible we have a function called Object.key() in JavaScript which gives you the collection of keys you have in your object:

Object.keys(thing);

which its result is:

["5", "gabba gabba"]

as you see there is no 2 or 3 in the keys, so if you want them to be there you should add a pair with these keys and your desired values:

thing[2] = "whatever";
thing[3] = "whatever";

then the key collection would be:

["5", "gabba gabba", "2", "3"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top