-6

It took me quite some time to realize that Object.keys() return and Array of strings that correspond to the object keys. This is well documented (but you have to read carefully :)).

My question is: what are the (technical) reasons for the returned Array to be made of keys cast to a string? (and not the keys themselves)

In my case the keys were integers, so I had to re-cast what .keys() returns through a .map()

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • 2
    Object keys are strings - always have been, always will be – Jaromanda X Sep 21 '22 at 11:22
  • 1
    _"In my case the keys were integers"_ - No. Only with an array or a `Map`/`WeakMap` – Andreas Sep 21 '22 at 11:22
  • even if you use a number as a key ... it's still going to be a string ... `Object.keys({1:1}).forEach(x => console.log(typeof x))` – Jaromanda X Sep 21 '22 at 11:24
  • [Keyed collections - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections#object_and_map_compared): _"Traditionally, objects have been used to **map strings** to values. ... The **keys of an Object are Strings** or Symbols, ..."_ – Andreas Sep 21 '22 at 11:25
  • In the example to which you linked, the keys are `"a"`, `"b"`, and `"c"`. What integer values do you expect those to be and why? In the majority of objects I've ever seen, property names are text. Usually semantically meaningful words like `"name"` or `"address"`. What integer values do you expect those to be and why? – David Sep 21 '22 at 11:26
  • Thanks to the comments pointing out that keys are always strings - good to know. It is disheartening to see downvotes instead of correcting me and helping to get a better grasp on the language... – WoJ Sep 21 '22 at 11:29

1 Answers1

3

In my case the keys were integers

They were not.

Object property names can only be strings or Symbols (ECMAScript, mdn).

The numbers (JS doesn't have an integer data type) were converted to strings when the property was created, not when the property names were read.

WoJ
  • 27,165
  • 48
  • 180
  • 345
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335