Javascript gotcha ! (if you come from Python)

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 indict){

// 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 indict){

console.log("Type of "+key+" is "+typeof(key))

}

Outputs

1

2

Type of1isstring

Type of2isstring

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