EN
JavaScript - check if string is empty / null / undefined
0 points
In this article, we would like to show you how to check if the string is empty / null / undefined in JavaScript.
Quick solution:
xxxxxxxxxx
1
const myString = '';
2
3
if (myString) {
4
console.log('myString is not empty');
5
} else {
6
console.log('myString is empty / null / undefined');
7
}
If you only want to check if a string is empty use this:
xxxxxxxxxx
1
if (myString === '') {
2
console.log('myString is empty');
3
} else {
4
console.log('myString is not empty');
5
}
xxxxxxxxxx
1
const isEmpty = (string) => {
2
return string ? false : true;
3
};
4
5
console.log( isEmpty('') ); // true
6
console.log( isEmpty(null) ); // true
7
console.log( isEmpty(undefined) ); // true
8
console.log( isEmpty('sample text') ); // false