Skip to content

JavaScript check if the string is empty | Example code

  • by

Use the strict equality operator (===) to check if the string is empty in JavaScript. This is because === will only return true if the values on both sides are of the same type, in this case, a string.

if(variable === "") {
}

Use !value. It works for undefined, null and even '' value:

Note: (false == “”) will return true, and (false === “”) will return false.

JavaScript checks if the string is empty

A simple example code check string is empty using the if condition statement.

<!DOCTYPE html>
<html>
<body>
  <script>

    var day = "";
    
    if (day === "") {
      console.log("String is empty")
    }

  </script>
</body>
</html> 

Output:

JavaScript check if the string is empty

But for a better check null also.

if(str === null || str === '')
{
    //enter code here
}

Do comment if you have any doubts or suggestions on this JS string empty topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading