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?

2
  • 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. Commented May 14, 2012 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... Commented May 14, 2012 at 10:35

2 Answers 2

3

you can check if index is in given array:

0 in a // => true
1 in a // => false
Sign up to request clarification or add additional context in comments.

Comments

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
}

2 Comments

same answer as mine but with a bit much explanation :)
I didn't see it, we've posted at the same time :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.