I hope people will forgive me a fairly basic JavaScript question (it's not generally a "primary" language for me). I was looking at W3Schools's JavaScript tutorial for review; their lesson on arrays has the following warning and code sample:
Warning: Adding elements with high indexes can create undefined "holes" in an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; // adds a new element (Lemon) to fruits
This will result in indices 4 and 5 containing undefined
.
Furthermore, I can do something like alert(fruits[20]);
(which gives me a popup saying "undefined") without exception.
In most languages that are more strict about typing, trying to do either of those actions would result in a runtime exception. I do realize that none of us on here were on the JavaScript design committee (as far as I know), but does anyone know why are these allowed (i.e. why don't they throw runtime exceptions or something like that)?
I can understand the purpose of doing something like fruits[4] = "Lemon"
(because that's essentially appending to the array), but is there ever a valid reason to do something like fruits[6] = "Lemon"
?
It also seems like doing something like alert(fruits[20]);
would almost always indicate a bug - I can't think of any legitimate use case for it actually. Is this correct?
My understanding from the answers to this question is that JavaScript arrays "are actually more like custom objects that use the properties as indexes" than they are like arrays in Java or C#. One of the answers also states
Javascript arrays are not true arrays like in C/C++ or other languages. Therefore, they aren't as efficient, but they are arguably easier to use and do not throw out of bounds exceptions.
Are these statements correct? Is this the reason for this behavior in JavaScript?