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)