Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a value is not null and not empty string in JS

Tags:

javascript

Is there any check if a value is not null and not empty string in Javascript? I'm using the following one:

var data; //get its value from db  if(data != null && data != '') {    // do something } 

But I'm wondering if there is another better solution. Thanks.

like image 971
ivva Avatar asked Apr 09 '17 17:04

ivva


People also ask

How do you check if a string is not null or empty in JavaScript?

Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty.

How do you check if a string is not empty or null?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.

How do you check if a value is empty or not in JavaScript?

Use the condition with “” and NULL to check if value is empty. Throw a message whenever ua ser does not fill the text box value.

How do you check if a variable is not null in JavaScript?

Use the strict inequality (! ==) operator to check if a variable is not null, e.g. myVar !== null . The strict inequality operator will return true if the variable is not equal to null and false otherwise.


2 Answers

If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:

if(data !== null && data !== '') {    // do something } 

Notice that I changed your code to check for type equality (!==|===).

If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:

if (data) {   // do something } 

Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).

The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.

like image 134
Gershon Papi Avatar answered Oct 02 '22 20:10

Gershon Papi


Instead of using

if(data !== null && data !== ''  && data!==undefined) {  // do something } 

You can use below simple code

if(Boolean(value)){  // do something  } 
  • Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false
  • Other values become true
like image 37
vipinlalrv Avatar answered Oct 02 '22 20:10

vipinlalrv