Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a string is empty

Short answer

An empty string has a length of zero:

const name = '';
 
console.log(name.length === 0);

Output:

true

Only spaces

A string of spaces is not empty. If spaces should not count, remove them with trim() first:

const name = '   ';
 
console.log(name.length === 0);
console.log(name.trim().length === 0);

Output:

false
true

null and undefined too

A value from a form or an API may be missing entirely. Optional chaining ?. handles that case:

const isBlank = (value) => !value?.trim();
 
console.log(isBlank(''));
console.log(isBlank('  '));
console.log(isBlank(undefined));
console.log(isBlank('Anna'));

Output:

true
true
true
false

Common mistake

A check like if (!value) treats the number 0 as empty too. Use it only when the value is surely a string:

const count = 0;
 
console.log(!count ? 'empty' : 'filled');

Output:

empty

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.