Step-by-Step Explanation:
Step 1: Declare the Array
Now nums
is:
Step 2: Use the delete
Operator
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:
Internally:
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
Yup! Even after deleting an item, the array length stays the same.
Step 3: Log the Array
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:
➤ Result: [1, 2, 4]
and length becomes 3