Understanding the Effect of delete on Arrays in JavaScript? – EPAM Interview Insight


Step-by-Step Explanation:

Step 1: Declare the Array

let nums = [1, 2, 3, 4];

Now nums is:

Index: 0 1 2 3
Value: [1, 2, 3, 4]

Step 2: Use the delete Operator

delete nums[2];

This line removes the value at index 2, but it does NOT reindex or shorten the array.

Important:

  • delete removes the value but leaves a hole (called a "sparse array").
  • It doesn’t affect the array’s length.

So after deletion:

nums = [1, 2, empty, 4];

Internally:

Index: 0 1 2 3
Value: [1, 2, empty, 4]

The value at index 2 is now undefined, but not explicitly. It's a missing slot — not the same as undefined.


NOTE :- Check the Length

console.log(nums.length); // 4

Yup! Even after deleting an item, the array length stays the same.


Step 3: Log the Array

console.log(nums);
// Output: [1, 2, empty, 4]

Depending on your environment:

  • Some will show: [1, 2, , 4]
  • Some (like Node.js) might show: [1, 2, <1 empty item>, 4]


✔ Final Answer:

D) [1,2,empty,4]

This question appeared in the Epam 2nd round of interview, testing the candidate’s knowledge of use of delete keyword with array in JavaScript.


Summary

Concept            Behavior
      delete nums[2]                        Removes the value at index 2
         Array stays same                                Length remains 4
   Index 2 becomes A "hole"                                (not undefined)

When to Avoid delete in Arrays

delete is not the recommended way to remove elements from arrays.

Instead, use:

  • .splice() removes and reindexes:

    nums.splice(2, 1); // removes 1 element at index 2

    ➤ Result: [1, 2, 4] and length becomes 3

Post a Comment

Previous Post Next Post