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:
trueOnly 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
truenull 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
falseCommon 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:
emptyFunctions used in this recipe
- String.prototype.trim — Removes whitespace from both ends of a string.
- String.prototype.length — The length of a string — how many characters it has.