You are currently viewing 2 Easy way to Check for Null or Empty Strings in JavaScript

2 Easy way to Check for Null or Empty Strings in JavaScript

JS String null or empty

While working with strings in JavaScript, developers often encounter situations where they need to check string. So, In this article, we will discuss about how to check for null or empty string in JS with example codes.

What is a null or empty string in JavaScript?

A null string is a string with no value assigned to it. In JavaScript, a null value is represented by the keyword null. On the other hand, an empty string is a string with no characters in it. In JavaScript, an empty string is represented by two quotation marks with nothing between them (” “).

Checking for null or empty strings in JavaScript

To check whether a string is null or empty in JavaScript, we can use conditional statements. Here is an example:

let str = ""; // empty string
if (str === null) {
    console.log("String is null");
} else if (str === "") {
    console.log("String is empty");
} else {
    console.log("String is neither null nor empty");
}

In this code:

  • We have declared the empty string ‘str’.
  • Then we use an if-else statement to check whether str is null or empty.
  • If str is null, we print “String is null”. If str is empty, we print “String is empty”. Otherwise, we print “String is neither null nor empty”.

So, we can use the ‘length’ property of a string to check for emptiness, like :

let str = ""; // empty string
if (str === null) {
    console.log("String is null");
} else if (str.length === 0) {
    console.log("String is empty");
} else {
    console.log("String is neither null nor empty");
}
  • In this above code, we have declared the empty string ‘str’ to check the string is null or empty.
  • Then we use the length property of the string str to check whether it is empty.
  • If str.length is 0, we print “String is empty”. Otherwise, we follow the same logic as before to check for null.
READ ALSO  What are JavaScript Bitwise Shift | How to use Shift operators

Conclusion

In JavaScript, a null string is a string with no value assigned to it, while an empty string is a string with no characters in it. To check whether a string is null or empty, we can use conditional statements. By checking strings, we can ensure that our JavaScript code missing input correctly.

Leave a Reply