How to check length of variable with property 'length' of undefined? [duplicate]

Tags: javascript
Question!

I have an variable, lets call it myNiceVar, I need to check myNiceVar value & length, myNiceVar variable is just undefined, which for JavaScript compiler this means the variable is defined but does not have any value yet

var myNiceVar;

if(myNiceVar.length){
  console.log("I have value!"); 
}else{
   console.log("I am empty"); 
}

Now JavaScript returns:

Uncaught TypeError: Cannot read property 'length' of undefined

How to check something like that and do not getting any error



Answers

Try this one

var myNiceVar;

if (myNiceVar !== null && typeof myNiceVar === 'object' && 'length' in myNiceVar) {
    console.log("I have value!");
} else {...}


You could check for typeof equals 'object' and if length is a key.

Do not forget to check for null first, because null is an object without properties.

var myNiceVar;

if (myNiceVar !== null && typeof myNiceVar === 'object' && 'length' in myNiceVar) {
    console.log("I have value!");
} else {
    console.log("I am empty");
}



An item of type undefined (and it is a type) has no length property - only items of type string and array do. Therefore, as @redneb notes, extend your condition to check for a non-falsy value before checking length.

if (myVar && myVar.length) { ... }
By : Utkanos


This video can help you solving your question :)
By: admin