-1

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const index in digits) {
  console.log(typeof digits[index]);
  console.log(digits[index]);
}


console.log('========================')

const digitsz = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
for (const indexz in digitsz) {
  console.log(typeof indexz);
  console.log(indexz);
}

ok now the return of the first typeof is number while the second one is string i dont know why is that ?? while in the array its already numbers in there

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Try with an array of booleans or of objects. That should show that only the first `typeof` tests the values in the array. – Bergi Apr 19 '20 at 19:18
  • 1
    The use of two separate arrays here is a complete red herring. The difference is what you are checking the type of and nothing to do with the differences between the arrays. – Quentin Apr 19 '20 at 19:18
  • In Javascript, everything is an object. Even Arrays. In the second loop, you are logging `indexz` which is a key in the array object and thus it is of type `string`. – rksh1997 Apr 19 '20 at 19:23

1 Answers1

0

'A for...in loop only iterates over enumerable, non-Symbol properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Object.prototype and String.prototype, such as String's indexOf() method or Object's toString() method. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).' https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in