How to check if a string is empty in JavaScript

You can use the length property to check if a string is empty in JavaScript. If the string's length is equal to 0, then it is empty. Otherwise, the string is not empty.

const str = ''

if (str.length === 0) {
  console.log(`String is empty ✅`)
} else {
  console.log(`String is not empty ❌`)
}

// String is empty ✅

If the string contains leading or trailing whitespace, you should use the trim() method to remove whitespace before checking if it is empty:

const str = '   '

if (str.trim().length === 0) {
  console.log(`String is empty ✅`)
} else {
  console.log(`String is not empty ❌`)
}

// String is empty ✅

The trim() method removes the leading and trailing spaces from a string. It returns an empty string if the string only contains spaces.

Alternatively, you could also use the strict equality operator (===) to check whether a string is empty or not:

const str = ''

console.log(str === '')             // true
console.log(0 === '')               // false
console.log(false === '')           // false
console.log([] === '')              // false
console.log(null === '')            // false
console.log(undefined === '')       // false

As you can see above, the strict equality operator returns false for null, undefined, and false values in the comparison because these are special values.

To check if a string is truthy and contains one or more characters, use the following code:

const str = 'js'

if (str) {
  // `str` variable is NOT false, undefined,
  // null, empty string, NaN
  console.log(`String is truthy 💯`)
}

// String is truthy 💯

A variable is truthy if it is not an empty string, 0, null, undefined, false, or NaN.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.