1

This code:

function sum(a) {
  let total = 0;
  for (let i in a) {
    if (typeof i !== 'number') {
      // throw new TypeError('sum(): elements must be numbers');
      console.log(i,typeof i);
    }
    total += i;
  }
  return total;
}

let ar = [1, 2, 3];

console.log(typeof ar[0]);
sum(ar);

outputs:

number
string
string
string

Why does the loop changes type? (as opposed to for/of loop, where the type is preserved)

mplungjan
  • 169,008
  • 28
  • 173
  • 236
milanHrabos
  • 2,010
  • 3
  • 11
  • 45
  • 4
    Properties of objects are always string (or symbol), even when you get them from an array object. Conclusion: don't use `for..in` on arrays. You probably wanted to use `for..of`, as you seem to want to sum the array *values*, not the array *indexes*. – trincot Apr 10 '21 at 18:36
  • 1
    Also `const sum = ar.reduce((a,b) => a+b)` – mplungjan Apr 10 '21 at 18:40

0 Answers0