James
James

Reputation: 2263

Why Does typeof array[0] == 'undefined' Not Work?

I want to check if the next element in the array exists before performing actions on it, but I can't check if it is undefined or not. For example:

// Variable and array are both undefined
alert(typeof var1);   // This works
alert(typeof arr[1]); // This does nothing

var arr = [1,1];
alert(typeof arr[1]); // This works now

Upvotes: 1

Views: 2064

Answers (2)

YardenST
YardenST

Reputation: 5256

when working with arrays, before you access an array index you should also check the array itself.

wrong:

if (arr[0] == ...)

good:

if (typeof arr != "undefined" and arr[0]==......

Upvotes: 0

Amber
Amber

Reputation: 526573

alert(typeof arr[1]); // This does nothing

It doesn't do anything because it's failing with an error:

ReferenceError: arr is not defined

If you try it this way instead:

var arr = [];
alert(typeof arr[1]);

Then you'll get what you expect. However, a better way to do this check would be to use the .length property of the array:

// Instead of this...
if(typeof arr[2] == "undefined") alert("No element with index 2!");

// do this:
if(arr.length <= 2) alert("No element with index 2!");

Upvotes: 6

Related Questions