Skip to content

JavaScript empty string | Example code

  • by

To define JavaScript empty a string use single quote or double quote without text.

var s; // undefined
var s = ""; // "" or ' '
s.length // 0

Test whether strValue is empty or is None

if (strValue) {
    //do something
}

Test wheter strValue is empty, but not None using strict operator

if (strValue === "") {
    //do something
}

JavaScript empty string

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script >
    var val;
    val = "";
    console.log(val)
    console.log(typeof(val))
  </script>
</body>
</html>

Output:

JavaScript empty string

Understanding use of empty string in Javascript

In JavaScript you can append text using the +=. For example:

x = ""
x += "Hello "
x += "World"
console.log(x); //Will print out "Hello World"

And so by declaring an empty string you can then append text to it.

What you are doing in your code is the same idea except you are doing the following:

And so you need the string deceleration in the beginning in order to append to it:

x = x + "Hello " //What is x? It is not declared...
x = x + "World"
console.log(x); 

Do comment if you have any doubts or suggestions on this Js empty data type 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. Required fields are marked *