How to Check for an Empty String in JavaScript
There are two main ways of checking for an empty string in JavaScript, which we will learn about in this tutorial.
The === Operator
The JavaScript strict equality operator (===
) checks whether a value is exactly equal to another and not just whether it is truthy or falsy. When evaluating an empty string with this operator the only thing that will make it return true
is another empty string.
console.log(undefined === "");
console.log(false === "");
console.log(0 === "");
console.log(null === "");
console.log("" === "");
false
false
false
false
true
The .length Operator
We can use the JavaScript .length
operator to check if the length of a string is 0 and thus empty like this:
var string1 = "hello"
var string2 = false;
var string3 = 0;
var string4 = ""
console.log(string1.length === 0);
console.log(string2.length === 0);
console.log(string3.length === 0);
console.log(string4.length === 0);
false
false
false
true
operator