Lets explain code step by step:
Step 1: Array Declaration
- We are creating an array
arr
using theconst
keyword. - The array initially contains three elements:
arr = [1, 2, 3]
- The indexes at this point:
- Important:
In JavaScript,
const
means you cannot reassign the variable reference, but you can still mutate (change) the contents of the array.
Step 2: Assigning a Value to arr[5]
- You are directly assigning a value at index 5.
- Current structure after this step:
- What happens to index 3 and index 4?
- They are automatically created as empty slots (also called "sparse elements").
- These empty slots are not
undefined
values—they are empty, meaning they don't exist in memory but are counted in the array length.
Step 3: Checking Array Length
-
The
.length
property of an array in JavaScript is always one more than the highest index. - In this case, the highest index is
5
. - So, the length becomes 6.