Check if String is Empty in JavaScript
To check if a given string is empty in JavaScript, compare the string with an empty string using the Equal-to comparison operator.
The boolean expression that compares the string str
and an empty string is:
str == ''
Let us write an if-else statement with this condition. If the value of str
is an empty string, the above expression returns true
and if block executes; otherwise the condition returns false
and else block executes.
if (str == '') {
console.log('str is empty');
} else {
console.log('str is not empty');
}
Examples
Let us go through some examples on how to check if a string is empty or not in JavaScript. We have also include detailed explanations for each example.
Example 1: Empty String
// Example 1: Empty String
var str = ''; // Initialize a variable with an empty string
if (str == '') { // Check if the string is empty
console.log('str is empty'); // If true, print 'str is empty'
} else {
console.log('str is not empty'); // Otherwise, print 'str is not empty'
}
Explanation: In this example, we define a variable str
and assign it an empty string (''
). Using an if
statement, we check whether str
equals an empty string. Since the condition evaluates to true
, the program outputs str is empty
.
Output: str is empty
Example 2: Non-Empty String
// Example 2: Non-Empty String
var str = 'apple'; // Initialize a variable with a non-empty string
if (str == '') { // Check if the string is empty
console.log('str is empty'); // If true, print 'str is empty'
} else {
console.log('str is not empty'); // Otherwise, print 'str is not empty'
}
Explanation: In this example, we define a variable str
and assign it a non-empty string ('apple'
). Using an if
statement, we check whether str
equals an empty string. Since the condition evaluates to false
, the program executes the else
block and outputs str is not empty
.
Output: str is not empty
Conclusion
In this JavaScript Tutorial, we learned how to check if a given string is empty or not using the Equal-to comparison operator, with detailed example programs and explanations.