Checking for a numerical index in a javascript array

jkushner picture jkushner · Jun 22, 2013 · Viewed 49.9k times · Source

I'm receiving json data that is aggregated by numerical indexes.

When I'm in my forloop, for example, the index might start at 1, which means in my forloop an error would occur because 0 doesnt exist.

How do I check if a numerical index exists in the javascript array?

Answer

andlrc picture andlrc · Jun 22, 2013
var a = [1, 2, 3], index = 2;

if ( a[index] !== void 0 ) { /* void 0 === undefined */
    /* See concern about ``undefined'' below.        */
    /* index doesn't point to an undefined item.     */
}