4

How do I now check if the value is defined as undefined, or if it's really not defined?
eg.

var a = [];
a[0] = undefined;

// a defined value that's undefined
typeof a[0] === "undefined";

// and a value that hasn't been defined at all
typeof a[1] === "undefined";

Is there a way to separate these two? it's possible touse a for-in loop to go through the array, but is there a lighter way?

Marcus
  • 5,083
  • 3
  • 32
  • 39
  • 2
    Undefined means it's undefined--if you explicitly set something to undefined, that's also undefined, by definition. You could use null, check the index against the array length, etc. – Dave Newton May 14 '12 at 10:15
  • True. I simplified my real problem for the question to make more sense. The array is really a collection from data, where undefined is a valid value that tells me something is not defined. The problems seem to come when the array is [undefined], and that made me wonder about the question topic... – Marcus May 14 '12 at 10:35

2 Answers2

3

you can check if index is in given array:

0 in a // => true
1 in a // => false
malko
  • 2,292
  • 18
  • 26
2

You can use the in operator to check if a given index is present in the array, regardless of its actual value

var t = [];
t[0] = undefined;
t[5] = "bar";

console.log( 0 in t ); // true
console.log( 5 in t ); // true
console.log( 1 in t ); // false
console.log( 6 in t ); // false

if( 0 in t && t[0] === undefined ) {
     // the value is defined as "undefined"
}

if( !(1 in t) ) {
    // the value is not defined at all
}
pomeh
  • 4,742
  • 4
  • 23
  • 44