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 check if the string is empty

Simple example code check string is empty using 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.