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.