Vlad Nikitin
Vlad Nikitin

Reputation: 13

js. array.indexOf after using delete

First of all - I know that I should use splice to delete elemnts from array to avoid empty spaces.

But I'm just curious. indexOf uses strong typing(===) so why it fails to find index of undefined?

var test_arr = [1, 2, 3];
delete test_arr[1];
console.log('indexOf', test_arr.indexOf(undefined));
console.log('check by index:', test_arr[1] === undefined);

Upvotes: 1

Views: 35

Answers (1)

gen_Eric
gen_Eric

Reputation: 227310

This is a little weird to explain but... undefined is both a value and a state.

When you do delete test_arr[1];, you are deleting that index. test_arr[1] no longer exists, it's not defined. When you try to access it, you'll get back the value undefined because that its state.

When you do .indexOf(), it searches over the values. test_arr[1] doesn't have a value.

For an interesting experiment, try this: test_arr[1] = undefined; and then do test_arr.indexOf(undefined).

Upvotes: 1

Related Questions