Check a string for empty, null, or undefined in JavaScript
This post will discuss how to check if a string is empty, null, or undefined in JavaScript.
There are several ways to check if a string is empty or null or undefined in JavaScript. Here are some of the most practical ways, along with examples:
1. Using logical NOT operator
The logical NOT (!) operator converts any value to a boolean, and returns the opposite of its truthiness. A string is considered falsy if it is empty, null, undefined, 0, false, or NaN. Truthy values include any other values. Therefore, we can use the ! operator to check if a string is falsy, and then negate it again to get the truthiness. Here’s an example:
|
1 2 3 4 5 6 7 8 9 |
// an empty string let str = ""; if (!str) { // str is falsy console.log("The string is either empty or null or undefined"); } else { // str is truthy console.log("The string is not empty, null, or undefined"); } |
2. Using strict equality operator
The strict equality operator (===) is a binary operator that returns true if the operands are equal and of the same type, and false otherwise. Therefore, we can use this operator to check if a string is exactly empty, null, or undefined by comparing it with the corresponding value. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
// an empty string let str = ""; if (str === "") { console.log("The string is empty"); } else if (str === null) { console.log("The string is null"); } else if (str === undefined){ console.log("The string is undefined"); } else { console.log("The string is not empty, null, or undefined"); } |
3. Using trim() function
This function removes any whitespace characters from both ends of a string. A string that contains only whitespace characters is considered empty, but it has a non-zero length. Therefore, we can use trim() function to check if a string is empty or contains only whitespace characters by calling it on the string and checking its length property. Here’s an example:
|
1 2 3 4 5 |
// a string with one space let str = " "; if (str.trim().length === 0) { console.log("The string is empty or contains only whitespace"); } |
That’s all about checking if a string is empty, null, or undefined in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)