If only JavaScript strings and numbers can be object literal keys can someone explain why this works in the console?
var obj = {null: 0, true: 1, false: -1}
> Object {null: 0, true: 1, false: -1}
obj.null
> 0
obj.true
> 1
obj.false
> -1
If only JavaScript strings and numbers can be object literal keys can someone explain why this works in the console?
var obj = {null: 0, true: 1, false: -1}
> Object {null: 0, true: 1, false: -1}
obj.null
> 0
obj.true
> 1
obj.false
> -1
Your keys aren't null
or true
but "null"
and "true"
.
Note that this isn't a conversion. The {key:value}
notation is another way to write {"key":value}
. There's no conversion happening in keys in the object literal notation, the quotes are simply optional when the key is a valid JavaScript identifier (which is the case for null
).
It's very different from what would have happened if you'd use the brackets notation (i.e. obj[true]=1
) : Anything that is not a string is converted to a string in order to be used as key in that case.
This distinction isn't obvious here but it may matter otherwise : you'd get something very different with
var a = {eval:1}; // no conversion, the key is "eval"
and
var a = {};
a[eval] = 1; // conversion, the key is eval.toString()
which would be the same (without cross-browser guarantee) as
var a = {"function eval() { [native code] }":1};
while
var a = {true:1};
would be equivalent to
var a = {};
a[true] = 1;
eval
function in your example