Computer >> Computer tutorials >  >> Programming >> Javascript

How to create undefined holes in an array in JavaScript?


To create undefined holes try to add elements at higher indexes, leaving smaller indexes untouched. Those leftover smaller indexes will be filled by undefined holes. To understand it in detail lets look at the following example.

Example

In the following example, only 3 elements were declared. Later on when at index 5, which was initially not present, another variable was assigned then the smaller indexes which were untouched were filled by undefined holes as shown in the output.  

<html>
<body>
   <script>
      var nums = [1,2,3];
      nums[5] = 6;
      var Len = nums.length;
      var text = "";
      for (i = 0; i < Len; i++) {
         text += nums[i] + "</br>";
      }
      document.write(text);
   </script>
</body>
</html>

Output

1
2
3
undefined
undefined
6