WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Check for an Empty String in JavaScript

Topic: JavaScript / jQueryPrev|Next

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. Please, check out the JavaScript data types chapter to learn more about it.


Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties