How to Check for an Empty String in JavaScript

Javascript check if string is empty example; In this tutorial you will learn how to check if a String is Empty in JavaScript;

In Js to check if a string is empty, you need to access string length and check if it’s equal to 0. If the string’s length is equal to 0, then the string is empty, otherwise it isn’t empty. Let’s see the below examples;

Example 1:

If string has not more spaces

const str = '';

if (typeof str === 'string' && str.length === 0) {
  console.log('string is empty');
} else {
  console.log('string is NOT empty')
}

Example 2:

If the empty string contains only spaces, use the trim() method to remove any leading or trailing whitespace before checking if it’s empty.

const str = '     ';

if (typeof str === 'string' && str.trim().length === 0) {
  console.log('string is empty');
} else {
  console.log('string is NOT empty');
}

Example 3:

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.

const str = 'coding driver';

if (typeof str === 'string' && str.length !== 0) {
  
  console.log("string is NOT empty")
}

Note: 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.