Questioning the Logic Behind Array Indexing
When delving into the world of programming, there is a certain excitement that comes with truly grasping the logic behind a language. The ability to navigate and problem-solve based on that logic is rewarding. However, encountering discrepancies in this logic can be puzzling.
Diving into Indexes
Exploring array indexes has led me to discover the following:
var fruit = ["Apple", "Orange", "Kiwi"]
fruit.length = 3 // gives the length of the fruit array
var rotten = fruit[2] // assigns "Kiwi" to the variable "rotten"
fruit[2] = "Melon" // changes the third element in the array from "Kiwi" to "Melon"
fruit[fruit.length] = "Melon" // adds a new element to the array after "Kiwi"
Unraveling the Mysteries of Logic
After using .length
to determine my array's length, I naturally expected to access the third element with var rotten = fruit[3]
. To my surprise, this returned undefined since indexing starts at 0, not 1.
A similar confusion arose when attempting to add an element with
fruit[fruit.length + 1] = "Melon"
, under the assumption that .length
refers to the last element. In reality, as per the 0-based index, it represents 2, not 3.
Pondering the Nature of Arrays
Is there a deeper rationale behind the choice of starting indexing at 0 instead of 1? Does this non-intuitive approach enhance JavaScript's functionality, or is it simply a rule to be accepted without questioning?