We can easily use JavaScript to check if a value is not undefined by using the conditional operation not equal to, !=. Let’s see this below.
if( value1 != undefined ){
//Value is not undefined
}
And here it is with a very simple example.
var value1 = 1;
if( value1 != undefined ){
console.log("value1 is not undefined");
}
#Output
value1 is not undefined
And it’s as simple as that. Now let’s see the not undefined check used in an example to remove undefined values from an array.
To remove undefined values from an array using JavaScript, one of the easiest ways to do this is to use a for loop with an if conditional statement. Here is a simple function we will create to remove undefined values from an array.
function removeUndefinedValues(arr){
var new_array = [];
for (var i=0; i
In the function above, we simply create a new array, loop through all the values of the old array, and only add values that are not undefined to the new array.
Notice above we also make use of the push() method. This simply adds the element to the end of the array.
And here is our function in use with an example array.
var array_of_strings = ["This",undefined,"is","an","array",undefined,"with","undefined",undefined,"values","."]
function removeUndefinedValues(arr){
var new_array = [];
for (var i=0; i
Hopefully this article has been useful for you to learn how to use Javascript to check if a value is not undefined.