- Test for Empty Values in Javascript
- The empty() Function: A Better Alternative
- Understanding the empty() Function
- Alternatives to Check for Empty Values
- Share This Article
- 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
Test for Empty Values in Javascript
Testing for empty values in JavaScript is a crucial aspect of programming, as it helps in validating data and maintaining the application’s integrity. JavaScript provides various data types, such as strings, numbers, booleans, objects, and arrays, and each type has its own set of characteristics when it comes to checking for empty values. In this article, we’ll discuss a precise and efficient function called empty() to check for empty values in JavaScript. We’ll cover its implementation, use cases, and compare it to other methods that developers can use to check for empty values, along with examples and common pitfalls.
Before diving into the empty() function, let’s look at some examples of JavaScript data types and how to check if they are empty:
- Strings: A string can be considered empty if it has a length of zero or contains only whitespace characters. You can check for an empty string using the length property or a regular expression:
const emptyString = ''; console.log(emptyString.length === 0); // true const whitespaceString = ' '; console.log(/^\s*$/.test(whitespaceString)); // true
- Numbers: Numbers are never considered empty, but you might want to check if they are zero, NaN (Not-a-Number), or Infinity:
const num = 0; console.log(num === 0); // true const notANumber = NaN; console.log(isNaN(notANumber)); // true const infinite = Infinity; console.log(infinite === Infinity); // true
- Booleans: Booleans can be either true or false , and they are never considered empty. However, you can check their values directly:
const bool = false; console.log(bool === false); // true
- Arrays: An array is empty if it has no elements. You can use the length property to check for empty arrays:
const emptyArray = []; console.log(emptyArray.length === 0); // true
- Objects: An object is empty if it has no enumerable properties. You can use a for. in loop or Object.keys() to check for empty objects:
const emptyObject = >; console.log(Object.keys(emptyObject).length === 0); // true
Common Developer Errors
- Using loose equality ( == ) can cause unexpected results when checking for empty values. For example, 0 == false returns true . Always use strict equality ( === ) for accurate comparisons.
- When checking for empty values in arrays or objects, make sure to account for cases where the variable might be null or undefined before using the length property or Object.keys() method.
- Be cautious about using the typeof operator when checking for empty values, as it returns the data type as a string, which can lead to confusion or errors if not used correctly.
The empty() Function: A Better Alternative
This custom empty() function combines the above situations and pitfalls to return check whether a variable is empty regardless of its data type.
Similar to PHP’s empty() function, our JavaScript function takes a variable or property and tells you if the value is empty by returning true or false . However, our JavaScript function is far more precise about what kinds of data can be considered empty:
- undefined or null
- a zero-length string
- an array with no members
- an object with no enumerable properties
- Booleans and numbers are never empty, irrespective of their value.
Here’s our empty() function’s code:
const empty = (data) => // Check if data is a number or boolean, and return false as they're never considered empty if (typeof data === 'number' || typeof data === 'boolean') return false; > // Check if data is undefined or null, and return true as they're considered empty if (typeof data === 'undefined' || data === null) return true; > // Check if data has a length property (e.g. strings, arrays) and return true if the length is 0 if (typeof data.length !== 'undefined') return data.length === 0; > // Check if data is an object and use Object.keys() to determine if it has any enumerable properties if (typeof data === 'object') return Object.keys(data).length === 0; > // Return false for any other data types, as they're not considered empty return false; >;
Understanding the empty() Function
The function uses four conditions to test different data types:
- Booleans and numbers: This condition always returns false. Providing this flexibility allows passing in arbitrary data.
- Undefined and null: Helpful for setting defaults for optional function arguments. Although null is obviously not the same as undefined , for many intents and purposes they amount to the same thing (i.e. this piece of data does not have a wanted value). For example, if you query a web storage object using object syntax, a value that isn’t defined will be undefined , yet the getItem() method will return null .
- Length property: Detects empty strings and arrays with no members. You can extend this condition to check for strings with only whitespace, but that depends on your specific use case.
- Objects: If the Object has no keys (enumerable properties), the object is deemed empty.
Alternatives to Check for Empty Values
Developers can also use built-in methods or libraries to check for empty values in JavaScript. Some popular alternatives include:
- Lodash’s _.isEmpty() method
- jQuery’s $.isEmptyObject() method
- The Array.isArray() method combined with the length property for arrays
Share This Article
Mark is the General Manager of SitePoint.com. He loves to read and write about technology, startups, programming languages, and no code tools.
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.