Why JavaScript Array Length Changes When You Add an Element at a Higher Index. JavaScript's Unexpected Behavior When Skipping Indexes. How Adding Elements at a Specific Index Affects Array Length

Why JavaScript Array Length Changes When You Add an Element at a Higher Index. JavaScript's Unexpected Behavior When Skipping Indexes. How Adding Elements at a Specific Index Affects Array Length

Lets explain code step by step:

const arr = [1, 2, 3];
arr[5] = 6; console.log(arr.length);

Step 1: Array Declaration

const arr = [1, 2, 3];
  • We are creating an array arr using the const keyword.
  • The array initially contains three elements:

arr = [1, 2, 3]

  • The indexes at this point:
Index: 0 1 2
Value: 1 2 3
  • 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]

arr[5] = 6;

  • You are directly assigning a value at index 5.
  • Current structure after this step:

        Index: 0 1 2 3 4 5
        Value: 1 2 3 <empty> <empty> 6
  • 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

console.log(arr.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.

✔ Final Answer:

C) 6

This question appeared in the Capgemini 2nd round of interview, testing the candidate’s knowledge of a array data type and array length calculation in JavaScript.

Post a Comment

Previous Post Next Post