- JavaScript Check Empty String – Checking Null or Empty in JS
- What’s the Difference Between Null and Empty?
- How to Check for Empty or Null in JavaScript
- How to Check for an Empty String in JavaScript with the length Property
- How to Check for an Empty String in JavaScript by String Comparison
- How to Check for Null in JavaScript
- How to Check for a Null or Empty String in JavaScript
- Conclusion
- How to Check if a String is Empty in JavaScript
- Tip
- How to Check if a String is Empty, null, or undefined
- 2. Comparing the Length of the String with 0
- 11 Amazing New JavaScript Features in ES13
- How to Check if a String is Empty or Null in JavaScript – JS Tutorial
- What are Empty and Null Strings?
- How to Check for Empty or Null Strings
- Using the if Statement and typeof Operator
- Using the length Property
- Using the trim Method
- Best Practices for Checking Empty or Null Strings
- Conclusion
JavaScript Check Empty String – Checking Null or Empty in JS
Joel Olawanle
There are a number of reasons why you might need to check if a string is empty or not. One of the most important reasons is when you’re retrieving data from a database, API, or input field.
In this article, you will learn how to check if a sting is empty or null in JavaScript. We will see many examples and methods you can use so that you can understand them and decide which one to use and when.
What’s the Difference Between Null and Empty?
Before we begin, you need to understand what the terms Null and Empty mean, and understand that they are not synonymous.
For example, if we declare a variable and assign it an empty string, and then declare another variable and assign it the Null value, we can tell them apart by looking at their datatype:
let myStr1 = ""; let myStr2 = null; console.log(typeof myStr1); // "string" console.log(typeof myStr2); // "object"
Looking at the code above, we can see that the compiler/computer interprets each value differently. So when it comes time to check, we must pass conditions for both types of values because we as humans frequently refer to null as empty.
How to Check for Empty or Null in JavaScript
We now know that an empty string is one that contains no characters. It is very simple to check if a string is empty. We can use two major methods that are somewhat similar because we will use the strict equality operator ( == ).
How to Check for an Empty String in JavaScript with the length Property
In this first method, we will check for the length of the string by adding the length property. We’ll check if the length is equal to 0 . If it’s equal to zero, it means that the string is empty, as we can see below:
let myStr = ""; if (myStr.length === 0)
The above will return this:
But this approach unfortunately might not work in all situations. For example, if we have a string that has white spaces as seen below:
let myStr = " "; if (myStr.length === 0) < console.log("This is an empty string!"); >else
"This is NOT an empty string!"
We can easily fix this error by first removing the white spaces using the trim() method before checking for the length of such string to see if it’s empty as seen below:
let myStr = " "; if (myStr.trim().length === 0) < console.log("This is an empty string!"); >else
This will now return the following:
Note: If the value is null, this will throw an error because the length property does not work for null.
To fix this, we can add an argument that checks if the value’s type is a string and skips this check if it is not:
let myStr = null; if (typeof myStr === "string" && myStr.trim().length === 0)
How to Check for an Empty String in JavaScript by String Comparison
Another way to check if a string is empty is by comparing the string to an empty string.
As with the previous method, if we have white spaces, this will not read the string as empty. So we must first use the trim() method to remove all forms of whitespace:
let myStr = " "; if (myStr.trim() === "") < console.log("This is an empty string!"); >else
Just as we did for the length method, we can also check for the type of the value so that this will only run when the value is a string:
let myStr = null; if (typeof myStr === "string" && myStr.trim() === "")
How to Check for Null in JavaScript
So far, we’ve seen how to check if a string is empty using the length and comparison methods.
Now, let’s see how to check if it’s null , and then check for both. To check for null , we simply compare that variable to null itself as follows:
let myStr = null; if (myStr === null)
How to Check for a Null or Empty String in JavaScript
At this point we have learned how to check for an empty string and also if a variable is set is null. Let’s now check to for both this way:
let myStr = null; if (myStr === null || myStr.trim() === "") < console.log("This is an empty string!"); >else
Conclusion
In this article, we learned how to check for an empty string or null and why they are not the same thing.
How to Check if a String is Empty in JavaScript
To check if a string is empty in JavaScript, we can compare the string with an empty string ( » ) in an if statement.
function checkIfEmpty(str) < if (str === '') < console.log('String is empty'); >else < console.log('String is NOT empty'); >> const str1 = 'not empty'; const str2 = ''; // empty checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty
To treat a string containing only whitespace as empty, call the trim() method on the string before comparing it with an empty string.
function checkIfEmpty(str) < if (str.trim() === '') < console.log('String is empty'); >else < console.log('String is NOT empty'); >> const str1 = 'not empty'; const str2 = ''; // empty const str3 = ' '; // contains only whitespace checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty checkIfEmpty(str3); // outputs: String is empty
The String trim() method removes all whitespace from the beginning and end of a string and returns a new string, without modifying the original.
const str1 = ' bread '; const str2 = ' milk tea '; console.log(str1.trim()); // 'bread' console.log(str2.trim()); // 'milk tea'
Tip
Trimming a string when validating required fields in a form helps ensure that the user entered actual data instead of just whitespace.
How to Check if a String is Empty, null, or undefined
Depending on your scenario, you might want to consider that the string could be a nullish value ( null or undefined ). To check for this, use the string if statement directly, like this:
function checkIfEmpty(str) < if (str) < console.log('String is NOT empty'); >else < console.log('String is empty'); >> const str1 = 'not empty'; const str2 = ''; // empty const str3 = null; const str4 = undefined; checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty checkIfEmpty(str3); // outputs: String is empty checkIfEmpty(str4); // outputs: String is empty
If the string is nullish or empty, it will be coerced to false in the if statement. Otherwise, it will be coerced to true .
To remove all whitespace and also check for a nullish value, use the optional chaining operator ( ?. ) to call the trim() method on the string before using it in an if statement.
function checkIfEmpty(str) < if (str?.trim()) < console.log('String is NOT empty'); >else < console.log('String is empty'); >> const str1 = 'not empty'; const str2 = ''; // empty const str3 = null; const str4 = undefined; const str5 = ' '; // contains only whitespace checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty checkIfEmpty(str3); // outputs: String is empty checkIfEmpty(str4); // outputs: String is empty checkIfEmpty(str5); // outputs: String is empty
The optional chaining operator lets us call the trim() method on a null or undefined string without causing an error. Instead, it prevents the method call and returns undefined .
const str1 = null; const str2 = undefined; console.log(str1?.trim()); // undefined console.log(str2?.trim()); // undefined
2. Comparing the Length of the String with 0
Alternatively, we can access the length property of a string and compare its value with 0 to check if the string is empty.
function checkIfEmpty(str) < if (str.length === 0) < console.log('String is empty'); >else < console.log('String is NOT empty'); >> const str1 = 'not empty'; const str2 = ''; // empty checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty
To check for strings containing only whitespace with this approach, we would also call the trim() method before comparing the length of the trimmed string with 0 .
function checkIfEmpty(str) < if (str.trim().length === 0) < console.log('String is empty'); >else < console.log('String is NOT empty'); >> const str1 = 'not empty'; const str2 = ''; // empty const str3 = ' '; // contains only whitespace checkIfEmpty(str1); // outputs: String is NOT empty checkIfEmpty(str2); // outputs: String is empty checkIfEmpty(str3); // outputs: String is empty
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.
How to Check if a String is Empty or Null in JavaScript – JS Tutorial
Joel Olawanle
In JavaScript, it’s important to check whether a string is empty or null before performing any operation. Trying to operate on an empty or null string can lead to errors, bugs, and unexpected results.
In this tutorial, we’ll explore the different ways of checking whether a string is empty or null in JavaScript and some best practices to follow when doing so.
What are Empty and Null Strings?
An empty string is a string that has no characters, while a null string is a string that has no value assigned to it. It’s important to differentiate between the two, as they are not the same.
For example, you have a form where a user can input their name. If the user doesn’t input anything, the input field’s value will be an empty string. However, the value will be null if the input field is not even created.
How to Check for Empty or Null Strings
JavaScript has several ways to check whether a string is empty or null. Let’s explore some of them.
Using the if Statement and typeof Operator
One way to check for an empty or null string is to use the if statement and the typeof operator. Here’s an example:
let str = ""; if (typeof str === "string" && str.length === 0) < console.log("The string is empty"); >else if (str === null) < console.log("The string is null"); >else
In this example, we’re checking whether the str variable is a string and whether its length is zero. If it is, then we know that it’s an empty string. If the str variable is null , then we know that it’s a null string. Otherwise, we know that the string is not empty or null.
Using the length Property
Another way to check for an empty string is to use the length property. Here’s an example:
let str = ""; if (str.length === 0) < console.log("The string is empty"); >else
In this example, we’re checking whether the str variable’s length is zero. If it is, then we know that it’s an empty string. Otherwise, we know that the string is not empty.
Using the trim Method
Sometimes, a string might contain whitespace characters that make it appear non-empty even when it is. In such cases, we can use the trim method to remove any leading or trailing whitespace characters before checking for emptiness. Here’s an example:
let str = " "; if (str.trim().length === 0) < console.log("The string is empty"); >else
In this example, we’re first using the trim method to remove any leading or trailing whitespace characters from the str variable, then checking whether the resulting string has zero length. If it does, then we know that the string is empty. Otherwise, we know that the string is not empty.
Best Practices for Checking Empty or Null Strings
Here are some best practices to follow when checking for empty or null strings in JavaScript:
- Always use triple equals ( === ) when comparing a string to null . This ensures that the types are checked, and you don’t accidentally compare a string to the number 0 or false .
- Use strict equality ( === ) when checking for an empty string. This ensures you don’t compare an empty string to a string containing only whitespace characters.
- Use the trim method to remove leading and trailing whitespace characters before checking for an empty string. This ensures that strings with only whitespace characters are also considered empty.
- Use regular expressions for more complex checks, such as checking for a string that only contains digits or checking for a string that matches a certain pattern.
let str = "12345"; let digitRegExp = /^\d+$/; if (digitRegExp.test(str)) < console.log("The string contains only digits"); >else
Conclusion
In this article, we’ve learned how to check whether a string is empty or null in JavaScript. We’ve explored different methods for doing so, such as using the if statement and typeof operator, the length property, and the trim method.
If you would like to learn more about JavaScript and web development, browse 200+ expert articles on web development written by me, and also check out my blog for more captivating content.