JS Daily #22 - Data Type of Object Keys

What is the output of following code?

const a = {};
const b = true;
a[b] = 20;
a["true"] = 30;

The output is 30.

a contains an empty object. b contains a boolean true value. This b is then used as a key in object a. An object key is always a string. So the boolean true is converted to string "true". Therefore in line 3, 20 is assigned to a["true"].

In line 4, the value 20 is replaced by 30 in the position a["true"].

In line 5, we are printing the value of a[true]. As we already mentioned, object keys will be always of string type. Therefore, a[true] is same as a["true"]. That is why, it prints 30 as output.