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

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration