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.
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.
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.
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.
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.
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.
Instead of using
if(data !== null && data !== '' && data!==undefined) { // do something }
You can use below simple code
if(Boolean(value)){ // do something }
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