How To Check If A String Is Empty/Null/Undefined In JavaScript


To check if a string is empty or null or undefined in Javascript use the following js code snippet.

var emptyString;
if(!emptyString){
 // String is empty
}

In JavaScript, if the string is empty or null or undefined IF condition returns false.

var undefinedString;
if(!undefinedString){
 console.log("string is undefined");
}

var emptyString="";
if(!emptyString){
 console.log("string is empty");
}

var nullString=null;
if(!nullString){
 console.log("string is null");
}

check if string is empty in JavaScript

check if string is empty in JavaScript

 

If the string is not undefined or null and if you want to check for empty string in Javascript we can use the length property of the string prototype as shown below.

var emptyString="";
if(emptyString && emptyString.length==0){
  console.log("string is empty");
}

Or you can directly check for the empty string with javascript Comparison operator “===” as shown below.

if(emptyString===""){
 console.log("string is empty");
}

 

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook or linkedn to get in touch with me.

Spread the word

Get free link to download 900+ Material Icons
Avatar
Arunkumar Gudelli

I am One among a million Software engineers of India. I write beautiful markup.I make the Web useful.

Related

Next
Previous