All keys are strings (unlike in Python)
Even though this is a basic, got me really hard times debugging my code after writing a lot in python, where this statement is not true. So if you have background in Python, make sure to be aware of following !!!
When iterating keys of dictionary / object in this manner
1 2 3 |
for ( key in dict ) { // code } |
Regardless of what type key you think should be, it’s going to be string. Consider following
1 2 3 4 |
dict = {1:100, "2":200} for ( key in dict ) { console.log("Type of " + key + " is " + typeof(key) ) } |
Outputs
1 2 |
Type of 1 is string Type of 2 is string |
Moreover, even thought you used key of type Number, you can still address it with String. Like this:
1 2 3 4 5 |
dict = {} dict[1] = 10 dict["2"] = 20 console.log(dict["1"]) console.log(dict[2]) |
In case you would expect this to ouput “Undefined” twice, you are wrong, because the output is
1 2 |
10 20 |
To put in contrast with python dictionary, in python things works differently. In python, the type of the used key is also used to has the value. So you can’ to followin in JavaScript, but can in Python
1 2 3 4 5 6 7 |
In [9]: m={1:"one", "1":"differentOne"} In [10]: m[1] Out[10]: 'one' In [11]: m["1"] Out[11]: 'differentOne' |