Check if String is Empty
To check if given string is empty in JavaScript, compare the given string with an empty string using Equal-to comparison operator.
The boolean expression that compares the string str
and an empty string is
str == ''
If the value is str
is an empty string, the above expression returns true, or else, the expression returns false. We can use this expression in an if-else statement as follows.
if (str == '') { //str is empty string } else { //str is not empty string }
Examples
In the following example, we take an empty string in str
, programmatically check if str
is empty string or not, and display the output in pre#output.
index.html
Since, the value in str
is an empty string, if-block executes.
In the following example, we take a non-empty string value in str
, say 'apple'
, programmatically check if str
is empty string or not, and display the output in pre#output.
index.html
Since, the value in str
is not an empty string, else-block executes.
Conclusion
In this JavaScript Tutorial, we learned how to check if given string is empty or not using Equal-to comparison operator, with example program.