Check if string is empty in JavaScript
In this tutorial, you are given a string. You should check if given string is empty or not.
Solution
A string is said to be empty if its length is 0
, or if it equals an empty string. To check if string length is 0
, we can use String.length property and comparison equal-to operator.
To check if string equals an empty string, we can use comparison equal value and equal type operator.
Program
1. In the following program, we are given a string in str
. We shall check if string str
is empty using string length property.
let str = '';
if ( str.length == 0 ) {
console.log('empty string');
} else {
console.log('not an empty string');
}
We have used the condition as a boolean expression in if-else statement
2. In the following program, we are given a string in str
. We shall check if str
is empty using equal-value and equal-type operator.
let str = '';
if ( str === '' ) {
console.log('empty string');
} else {
console.log('not an empty string');
}