Hao Wu
Hao Wu

Reputation: 20834

How exactly do javascript numeric property names work?

Can someone explain this behavior?

const obj = {};

obj[0] = 0;

console.log(obj['0']);  // 0

obj[0.1] = 0.1;

console.log(obj['0.1']);  // 0.1

obj[1.0] = 1.0;

console.log(obj['1.0']);  // undefined

It seems javascript converts the string integer numbers into an integer, but not exactly how it works in the calculation. Since string '1.0' should be the same as 1.

Also is it possible to set 2 distinct attributes for one object of number 0 and string "0"? Can I avoid javascript convert the string into numbers while doing object lookup?

Upvotes: 1

Views: 64

Answers (1)

JLRishe
JLRishe

Reputation: 101728

JavaScript property names are all strings.

In this line:

obj[1.0] = 1.0;

1.0 is first coerced to the string value '1', and then 1.0 is assigned to obj['1'].

You can retrieve it the same way, if you pass in a number instead of the string value 1.0. The same string conversion will be applied for property retrieval:

const obj = {};

obj[1.0] = 1.0;

console.log(obj[1.0]);  // 1

However, the fact that the property names are strings is a little irrelevant here. Even if it had actual numeric property names, 1.0 would evaluate to the number 1 and the value would be assigned to obj[1] anyway.

Also is it possible to set 2 distinct attributes for one object of number 0 and string "0"? Can I avoid javascript convert the string into numbers while doing object lookup?

No, 0 and '0' both evaluate to the property name '0'.

Upvotes: 5

Related Questions