Sling Academy
Home/JavaScript/2 Ways to Check if a String is Empty in JavaScript

2 Ways to Check if a String is Empty in JavaScript

Last updated: February 27, 2023

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

Next Article: 3 Ways to Reverse a String in JavaScript

Previous Article: JavaScript: Regular Expressions Cheat Sheet

Series: JavaScript Strings

JavaScript

You May Also Like

  • Can JavaScript programmatically bookmark a page? (If not, what are alternatives)
  • Dynamic Import in JavaScript: Tutorial & Examples (ES2020+)
  • JavaScript: How to implement auto-save form
  • JavaScript: Disable a Button After a Click for N Seconds
  • JavaScript: Detect when a Div goes into viewport
  • JavaScript Promise.any() method (basic and advanced examples)
  • Using logical nullish assignment in JavaScript (with examples)
  • Understanding WeakRef in JavaScript (with examples)
  • JavaScript Numeric Separators: Basic and Advanced Examples
  • JavaScript: How to Identify Mode(s) of an Array (3 Approaches)
  • JavaScript: Using AggregateError to Handle Exceptions
  • JavaScript FinalizationRegistry: Explained with Examples
  • JavaScript String replaceAll() method (with examples)
  • Nullish Coalescing in JavaScript: A Developer’s Guide
  • JavaScript Promise.allSettled() method (with examples)
  • JavaScript: Checking if the current window is a popup
  • JavaScript: Checking if the current window is fullscreen
  • JavaScript: Checking if a Div element is visible
  • JavaScript: How to programmatically reload/close the current page