Check if String is Empty in JavaScript

Check if String is Empty in JavaScript

In this tutorial, we will see how to check if string is empty in JavaScript.

In JavaScript, we can check it using its truthy value or by using the === operator.

Check empty string using truthy value in JavaScript.

In JavaScript, truthy value are those values that evaluates to boolean true when encountered in a Boolean context.

JavaScript uses type conversion in Boolean contexts.

Some examples of truthy values :

if (true)
if ({})
if ([])
if (42)
if ("false")

All of the output will be true.

So now we just have to check whether there is a truthy value in the string by:

let string = '';
if (string){
  console.log('Not Empty')
} else {
  console.log('Empty String')

If condition is true, it will return "Not Empty" or else it will return "Empty String".

Check empty string using ==== operator in JavaScript.

The strict equality operator (===) is use to check whether the string is empty or not.


let str = " ";

function isEmpty(string){
  if (string.length === 0 || !string.trim()){
    console.log('Empty String')
  } else {
    console.log('String Not Empty')

In the above code, string.length === 0 check if the length of the string is 0 and !string.trim() checks if the string is not made of white-space only.

So now, when string.length === 0 || !string.trim() condition returns true, it means the string is empty and it will print our "Empty String " and if it returns false, it will print "String Not Empty" in the console.

Related Topic:

Check if a string contains a substring in Javascript

Convert String To Float in JavaScript

How to Check if Object is Empty in JavaScript

How to compare two strings in JavaScript?

How To Check Null Values In JavaScript?