Is it ok to use float numbers as keys in javascript objects? Woudn't be there potential problems with such objects?
Consider the below code:
var obj = {};
obj[1.2345] = 10;
obj[10000] = 10;
obj[10000.23] = 10;
Is it ok to use float numbers as keys in javascript objects? Woudn't be there potential problems with such objects?
Consider the below code:
var obj = {};
obj[1.2345] = 10;
obj[10000] = 10;
obj[10000.23] = 10;
Share
Improve this question
edited Mar 13, 2014 at 9:04
Jino
3651 gold badge2 silver badges18 bronze badges
asked Mar 13, 2014 at 8:57
Prosto TraderProsto Trader
3,5273 gold badges33 silver badges53 bronze badges
2
- 2 Not except for the fact that you have to access the properties using the bracket notation – Johan Commented Mar 13, 2014 at 8:59
- 1 Probably best, if you're going to state your question two ways, to make them not opposites of each other. E.g., the answer to "Is it ok to use float numbers as keys in javascript objects?" is mostly "yes," but the answer to "Woudn't be there potential problems with such objects?" is mostly "no". – T.J. Crowder Commented Mar 13, 2014 at 9:06
1 Answer
Reset to default 11Is it ok to use float numbers as keys in javascript objects?
Yes, mostly. All property names (keys) are strings* (even the ones we think of as array indexes, in JavaScript's standard arrays, because those aren't really arrays). So when you write
obj[1.2345] = 10;
what you're really writing is:
obj[String(1.2345)] = 10;
e.g.
obj["1.2345"] = 10;
and it's perfectly fine to have a property with the name 1.2345
(as a string) in an object.
The reason I said "mostly" above is that the floating-point numbers used by JavaScript (and most other languages) aren't perfectly precise; so if you did this:
obj[0.3] = 10;
and then
var key = 0.1;
key += 0.2;
console.log(obj[key]); // undefined
That's undefined because 0.1 + 0.2
es out to 0.30000000000000004
, rather than 0.3
, and your object doesn't have a property named 0.30000000000000004
.
* "...all property names...are strings..." This was true up through ES5, but as of ES2015 (aka ES6), there's a new property name type: Symbol
. But most properties have string names, the use cases for Symbol
are important but outnumbered by "normal" property names.