JavaScript Code

How to check if string is empty?


Problem Statement

check if given string is empty

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. given string is str. check if string str is empty using string length

let str = '';
if ( str.length == 0 ) {
    console.log('empty string');
} else {
    console.log('not an empty string');
}

we have used the condition in if-else statement

2. given number is str. 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');
}