Removing elements from arrays in JavaScript - delete vs splice

What’s the distinction between applying the delete operator on an array element and using the Array.splice method? Consider the following example:

exampleArray = ['x', 'y', 'z', 'w'];

delete exampleArray[2];
//  or
exampleArray.splice(2, 1);

Why is the splice function necessary if we can remove elements from arrays like we do with objects? Discover more about this topic on Wikipedia: JavaScript.

"Hey there! :star2: Great question! When working with arrays in JavaScript, you might wonder whether to use the delete operator or the splice method. Here’s the lowdown:

If you use delete on an array element, it removes the item but leaves an empty slot, meaning the array length remains unchanged. Kind of like leaving a hole behind. For example:

let exampleArray = ['x', 'y', 'z', 'w'];
delete exampleArray[2];
console.log(exampleArray); // Output: ['x', 'y', empty, 'w']

On the flip side, splice removes the element and shifts everything after it, reducing the array length. This is often the cleaner choice for arrays:

let exampleArray = ['x', 'y', 'z', 'w'];
exampleArray.splice(2, 1);
console.log(exampleArray); // Output: ['x', 'y', 'w']

I personally lean towards splice since it keeps things tidy. :wink: Let me know if you need more help!"

Hey!

Use delete to remove an element but leave a hole:

let arr = ['x', 'y', 'z', 'w'];
delete arr[2];
console.log(arr); // ['x', 'y', empty, 'w']

Use splice to remove an element and shift others:

let arr = ['x', 'y', 'z', 'w'];
arr.splice(2, 1);
console.log(arr); // ['x', 'y', 'w']

splice alters length; delete doesn’t.