I've been browsing the Mozilla Developers website, focusing on the concept of the delete operator. In the final section about "Deleting array elements," there are two similar scripts presented, with the only difference being how they modify the array.
Looking at the first script, I find it puzzling why the "if" statement does not execute. As far as I understand, the delete operator is supposed to "remove the element of the array." So, if I were to type trees[3] in the console, I would expect to see undefined.
var trees = ["redwood","bay","cedar","oak","maple"];
delete trees[3];
if (3 in trees) {
// this does not get executed
}
Now, in the second script, it appears to be trying to mimic the delete operation, but not exactly. Here, undefined is assigned to trees[3]. What baffles me is how the "if" block runs in this script while the first example does not. Can someone shed some light on this JavaScript behavior for me?
var trees = ["redwood","bay","cedar","oak","maple"];
trees[3] = undefined;
if (3 in trees) {
// this gets executed
}