How can I check if a variable is empty in Javascript? Sorry for the stupid question, but I'm a newbie in Javascript!
if(response.photo) is empty {     do something else {     do something else }   response.photo was from JSON, and it could be empty sometimes, empty data cells! I want to check if it's empty.
Java String isEmpty() Method This method returns true if the string is empty (length() is 0), and false if not.
You can use lodash: _. isEmpty(value). It covers a lot of cases like {} , '' , null , undefined , etc. But it always returns true for Number type of JavaScript primitive data types like _.
Use the === Operator to Check if the String Is Empty in JavaScript. We can use the strict equality operator ( === ) to check whether a string is empty or not. The comparison data==="" will only return true if the data type of the value is a string, and it is also empty; otherwise, return false .
Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .
If you're testing for an empty string:
if(myVar === ''){ // do stuff };   If you're checking for a variable that has been declared, but not defined:
if(myVar === null){ // do stuff };   If you're checking for a variable that may not be defined:
if(myVar === undefined){ // do stuff };   If you're checking both i.e, either variable is null or undefined:
if(myVar == null){ // do stuff }; 
                        This is a bigger question than you think. Variables can empty in a lot of ways. Kinda depends on what you need to know.
// quick and dirty will be true for '', null, undefined, 0, NaN and false. if (!x)   // test for null OR undefined if (x == null)    // test for undefined OR null  if (x == undefined)   // test for undefined if (x === undefined)  // or safer test for undefined since the variable undefined can be set causing tests against it to fail. if (typeof x == 'undefined')   // test for empty string if (x === '')   // if you know its an array if (x.length == 0)   // or if (!x.length)  // BONUS test for empty object var empty = true, fld; for (fld in x) {   empty = false;   break; } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With