JavaScript Array Undefined Items

· 1 min read · 165 Words · -Views -Comments

Recently encountered an issue where array iteration counts were incorrect due to uninitialized elements. This led to the discovery that array iteration counts don’t necessarily match the array length. Here’s a summary of this pitfall.

Example

 let array = [undefined, , 1, 2, 3];
      console.log(array[0]); // undefined
      console.log(array[1]); // undefined

      array.forEach((item, idx) => {
        console.log(item, idx);
      });

Output result:

Analysis

  1. Whether you assign undefined to an array item or leave it uninitialized, the value will be undefined

  2. During iteration, assigned items will be traversed, but unassigned items are skipped directly

    For example, when you need to control a fixed number of loops, you might write it like this. Note that fill() ensures array items are assigned as undefined. If you omit this, the iteration count will be 0

     new Array(10).fill().forEach((_, idx) => {
            console.log(idx + 1);
     });
    
Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover