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("\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?


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);

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){

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.

In general, arrays in JavaScript are sparse – they can have holes in them (That's why indexOf() returns -1 ), because an array is simply a map from indices to values. The array you are looking for is called dense it looks like

var a = Array.apply(null, Array(3)) 


var a = Array(undefined, undefined, undefined) 
a.indexOf(undefined) //0

Please have a look at this post, i hope it will help you

Need Your Help

Click event is geting fired twice in modular Backbone application

jquery backbone.js

I am creating a sample Modular backbone application. I am loading different view with the help of router.In one of my view I have a button which has a click event function defined.

API hooking fails using JMP instruction

c windows winapi hook detours

I am intercepting a Win32 function call using JMP instruction which as given at JMP interception