Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why array.indexOf(undefined) doesn't work if array is sparse

I'm new at JavaScript and there is one thing that bothers me. I have got a very simple code:

var a = [];
a[1] = 1;

i = typeof(a[0]);
index = a.indexOf(undefined);
len = a.length;

console.log(a);
console.log("\n" + len);
console.log("\n" + i);
console.log("\n" + index);

My question is: Why indexOf returns -1, instead of 0. I know that this method compare by ===, but I used as a parameter keyword undefined. If I change method parameter to "undefined" it also doesn't work (but this for me it's obvious). Can someone explain me this and tell what is the simpliest way to find undefined value in array?

like image 855
JohnDoe Avatar asked Mar 11 '16 20:03

JohnDoe


1 Answers

This will in fact find an undefined value in an array, the problem is that your array a doesn't have any undefined values in it, so it returns -1 meaning it did not find any. Your array looks like:

[*uninitialized*, 1]

The fact that you put nothing in the first position doesn't mean it's populated with an undefined, it simply is not initialized/does not exist.

If you did something like:

var a = [undefined, 1];
var index = a.indexOf(undefined);
console.log(index);

It will in fact print 0 as expected.

Edit: to answer your question of how to find an uninitialized value, do the following

var a = [];
a[1] = 1;

for(var i = 0; i < a.length; i++){
    if(a[i] === undefined){
      console.log(i);
    }
}

This will print the index of uninitialized array values. The reason this actually works unlike indexOf is that a[i] will evaluate to undefined if:

(1) The element exists and it has the value undefined, or

(2) The element doesn't exist at all. indexOf however will skip these "gaps" in the array.

like image 145
Pabs123 Avatar answered Oct 13 '22 01:10

Pabs123