How to check if a String is Empty in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 06 20212 min read

Check if a String is Empty in JavaScript #

To check if a string is truthy and contains one or more characters add the string to an if statement.

index.js
const str = 'hello'; if (str) { // if this code block runs // ๐Ÿ‘‰๏ธ str is NOT "", undefined, null, 0, false, NaN console.log("string is truthy") }

The code in the if block wouldn't run if the str variable is set to an empty string, undefined, null, 0, false or NaN.

To be explicit you can check if the string is equal to an empty string.

index.js
const str = ''; if (typeof str === 'string' && str !== '') { // if this code block runs // ๐Ÿ‘‰๏ธ string is NOT empty }
We have 2 checks in the if statement. We first check if the contents of thestr variable are of type string. This is very important, because comparing an empty string to any other type would bring confusion into our code.

The && (AND) characters signify that both conditions have to be true for the if block to run.

This approach wouldn't work for a string, that contains an empty space " ". In that scenario we have to trim the space before checking if the string is empty.

index.js
const str = ' '; if (typeof str === 'string' && str.trim() !== '') { // if this code block runs // ๐Ÿ‘‰๏ธ string is NOT empty }
We first make sure that the str variable contains a string and then we call the String.trim method. If we try to call the trim method on a variable that is set to undefined or null we would get an error.

The String.trim method returns a new string with the whitespace from both ends of a string removed.

index.js
const str = ' hello '; const trimmed = str.trim(); console.log(trimmed) // ๐Ÿ‘‰๏ธ 'hello'
This is very useful when you're taking user input and want to make sure that the user didn't just enter a whitespace character to get around your validation.

We can check if a string is empty by accessing its length property. If the string has a length of 0, then it is empty.

index.js
const str = 'hello'; if (typeof str === 'string' && str.length !== 0) { // if this code block runs // ๐Ÿ‘‰๏ธ string is NOT empty console.log("string is NOT empty") }
Note that if you try to access the length property on a variable that is undefined or null you would get an error. Make sure that the variable is set to a string before you try to access its length property.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee