0

I'm super interested in what the heck is going on the below code:

// 1.

let arr = [];
console.log(arr);
// []
// Totally ok and normal

// 2.

arr[5] = 404;
console.log(arr);
// (6) [empty * 5, 404]
// Absolutely nothing. it just works I know

// 3.

console.log(arr[0]);
// undefined
// No problem till here

// 4.

for (let idx in arr) {
  console.log(idx);
}
// 5


// 5.

arr[0] = undefined

for (let idx in arr) {
  console.log(idx);
}

// 0
// 5
// Wait, what?

Upon the step 3, arr[0] logged undefined and when I explicitly give a undefined to arr[0], it counted as an index in arr.

Can someone please explain this magic?

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
Lee
  • 62
  • 1
  • 9
  • 1
    use `for..of` or old school `for` loop for arrays. – DecPK Sep 14 '21 at 01:04
  • 2
    There is a [specification](//tc39.es/ecma262/), so it’s safe to rule out magic. – Sebastian Simon Sep 14 '21 at 01:04
  • 2
    "*Is there something like "implicit undefined" and "explicit undefined" thing*" - yes. You get the implicit `undefined` when trying to access a property that doesn't exist. But you can also explicitly store the value `undefined` in a property. Compare `const o = {x: undefined}; console.log(o.x, o.y); console.log("x" in o, "y" in o);` – Bergi Sep 14 '21 at 01:08
  • 3
    Remember, array are just objects that have numeric keys. Just like ordinary objects, there's a difference between a property that doesn't exist and a property whose value is `undefined`. – Barmar Sep 14 '21 at 01:08
  • Thank you so much, You guys helped me out a lot! – Lee Sep 14 '21 at 01:09

0 Answers0