Q:

How to Check for an Empty String in JavaScript

0

How to Check for an Empty String in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the === Operator

You can use the strict equality operator (===) to check whether a string is empty or not.

The comparsion str === "" will only return true if the data type of the value is string and it is not empty, otherwise return false as demonstrated in the following example:

<script>
if(str === ""){
    // string is empty, do something
}
    
// Some test cases
alert(2 === "");  // Outputs: flase
alert(0 === "") // Outputs: false
alert("" === "") // Outputs: true
alert("Hello World!" === "") // Outputs: false 
alert(false === "") // Outputs: false
alert(null === "") // Outputs: false
alert(undefined === "") // Outputs: false
</script>

As you can see the values null, undefined, false returns false in the comparision, because they are special values. 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Sort an Array of Integers Correctly in Java... >>
<< How to Get the Class Name of an Object in JavaScri...