0

I have this object:

const someobj = {
  100: 'a',
  200: 'b',
  300: 'c'
}

for (const prop in someobj) {
  console.log(prop)
  console.log({ prop: prop })
}

When running it i get this output:

100
{ prop: '100' }
200
{ prop: '200' }
300
{ prop: '300' }

Why are the prop values converted from a number to a string? Is there anyway to avoid this besides doing Number(prop)?

Andreas
  • 1,091
  • 1
  • 11
  • 16

1 Answers1

1

Object properties are always strings (or symbols). Even though you can define an object with a numeric property, or by putting a number into bracket notation, the property itself will still be a string.

const obj = { 1: 'one' };
const [prop] = Object.keys(obj);
console.log(prop, typeof prop);

When you extract a property from an object using for..in, or Object.keys, or any other method, it will be a string (or a symbol). To make it be a number instead, you need to cast it to a number explicitly, like you're doing in your question.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320