Holes in Arrays

Adding elements with high indexes can create undefined "holes" in an array. In the following example, the holes are indexed at 4 to 9 and will return "undefined":

  declare variable = ["Banana", "Orange", "Apple", "Mango"];
  fruits[10] = "Peach";
   <== adds a new element (Peach) to fruits, and creates "holes" at indexes [4 to 9]

HTML file: Displayed by browser:
<body>
<!--ORIGINAL ARRAY-->
<h4>The original array:</h4>
<p id="demo"></p>
<hr />
<!--ADD PEACH TO ARRAY BUT CREATE HOLES-->
<h4>Add element with high index:</h4>
<button onclick="myHole()">Element at Index [8]</button>
<p id="holes"></p>
<script>
var fruits = [
    "Banana",
    "Orange",
    "Apple",
    "Mango"
];
document.getElementById("demo").innerHTML = fruits;
/*ADD PEACH BUT CREATE HOLES*/
function myHole() {
    fruits[10] = "Peach";
    document.getElementById("holes").innerHTML = fruits[8];
}
</script>
</body>

The original array:


Add element with high index:


BackTable of ContentsNext