Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking something isEmpty in Javascript?

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.

like image 734
Jhon Woodwrick Avatar asked Jan 04 '11 20:01

Jhon Woodwrick


People also ask

Is there an isEmpty in JavaScript?

Java String isEmpty() Method This method returns true if the string is empty (length() is 0), and false if not.

How do you check if a value is empty?

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 _.

How check string is null in JavaScript?

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 .

How check object is null or not in JavaScript?

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 .


2 Answers

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 }; 
like image 91
brettkelly Avatar answered Oct 15 '22 21:10

brettkelly


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; } 
like image 44
Hemlock Avatar answered Oct 15 '22 22:10

Hemlock