2 Ways to Check if a String is Empty in JavaScript

Updated: February 27, 2023 By: Khue Post a comment

An empty string is a string that contains no characters at all. This concise article shows you 2 different ways to check whether a given string is empty or not in JavaScript.

Note: A string that contains only whitespace characters, such as spaces, tabs, or line breaks, is NOT considered an empty string in JavaScript.

Using the length property

The easiest way to check if a string is empty is to use the length property. If the length of the string is zero, it means that the string is empty.

Example:

const s1 = '';
const s2 = '   ';

if (s1.length === 0) {
  console.log('s1 is empty');
} else {
  console.log('s1 is not empty');
}

if (s2.length === 0) {
  console.log('s2 is empty');
} else {
  console.log('s2 is not empty');
}

Output:

s1 is empty
s2 is not empty

See also: Remove Leading & Trailing Whitespace from a String in JavaScript

Using the === operator

You can also check if a string is empty using the === operator. If the string is equal to an empty string (“”), it means that the string is empty.

Example:

const str = '';
if (str === '') {
  console.log('String is empty');
} else {
  console.log('String is not empty');
}

Output:

String is empty