As an illustration, I start by creating a constructor and initializing an array of objects in JavaScript.
function SomeConstruct(val1, val2) {
this.val1= val1;
this.val2= val2;
}
var someCons= new Array();
someCons[0] = new SomeConstruct(12, 40);
someCons[1] = new SomeConstruct(34, 42);
someCons[2] = new SomeConstruct(0,-5);
Subsequently, I attempt to create a new object with index [5], even though the last valid index of the array is [2].
someCons[5]=new SomeConstruct(43,232);
While this code appears to work fine, attempting to access objects at indices [3] or [4] results in an error.
Is there a way to prevent this behavior? For example, if I have a loop where I add new objects to the array based on certain conditions (e.g., when val1==1), how can I ensure that I do not skip indices and create out-of-bounds elements like [5] instead of [3]? Why does JavaScript allow for this kind of behavior?