user1740058
user1740058

Reputation: 45

check if variable undefined

Need to check if an array item at a specific index contains a value. The array index may or may not be defined, the array may or may not be defined. The value at the index could be number, string, or empty string - if index is defined at all.

is there anything wrong with

edit - removed quotes

if(undefined===array[0]){
    console.log('undefined');
}

Upvotes: 2

Views: 81

Answers (2)

Tomek Sułkowski
Tomek Sułkowski

Reputation: 7201

Actually yes, you've mistaken "undefined" type with undefined value.

You can write either:

if (undefined === array[0]) {
    console.log('undefined');
}

or

if ('undefined' === typeof array[0]) {
    console.log('undefined');
}

And if array itself may be undefined, you should of course add the check for if before, e.g.:

if (undefined === array || undefined === array[0]{
    console.log('undefined');
}

Upvotes: 3

Jan
Jan

Reputation: 5815

@Tomek already has an excellent answer but I would still like to chime in here. One of your main problems is that you're mixing data types in your array, you shouldn't be doing that. If your array should contain strings and strings ONLY you can easily check it like this

if(typeof array[0] === "string" && array[0] !== "")

which would be a javascript equivalent of for example C#'s !string.IsNullOrEmpty.

Having multiple data types in the array complicates the checking and is indicative of an error in structuring your code. What happens for example if you enter null into the array? Then Tomek's test will fail. Of course, you could also do another check for null but I'd say it would be better to restructure your data model.

Upvotes: 0

Related Questions