Guinea guinea
Guinea guinea

Reputation: 53

Why 'delete' replaces value with undefined in arrays but in objects it is able to remove the property completely?

What differences in object and arrays cause this? Why is Object able to remove the element and array cannot? Does Object automatically makes a check to not display undefined values?

Upvotes: 0

Views: 44

Answers (1)

Quentin
Quentin

Reputation: 944054

delete will remove properties entirely from arrays.

const array = [0,1,2];
delete array[1];
console.log("0" in array);
console.log("1" in array);

Since most tools that display an array for debugging purposes will not display them with explicit index values, any missing values will typically be rendered as undefined.

If they didn't then you wouldn't be able to tell the difference between these two examples:

const sparse = [1,,2];
const full = [1,2];

console.log(sparse);
console.log(full);

If you want to shuffle the indexes of every subsequent item down the array, then you need to look at the splice method.

Upvotes: 1

Related Questions