Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

Today, I’m going to show you how do you check if a string is empty or undefined in javascript, here I will use some common syntax to check string is empty, undefined, or have some value.

The javascript if... else statement auto handles these types of cases like null, undefined, NaN, empty string (""), 0, and false.

For all of these cases it will think falsy values, so to handle empty or undefined we have to just if... else statement.

Let’s start today’s tutorial How to check if a string is empty or undefined in javascript?

Here, we will take the example of an undefined, empty, and valid string value to check whether actually if... else statement can handle it or not.

Let’s plan out what we are going to do.

  1. create variables that store undefined, empty, and valid string value
  2. check the undefined value in the if...else statement
  3. check the empty value in the if...else statement
  4. check the string value in the if...else statement
// create variables which store undefined, empty and valid string value
const str1 = undefined;
const str2 = "";
const str3 = "infinitbility";

// check undefined value in `if...else` statement
if(str1){
  console.log("str1 is a valid value");
} else {
  console.log("str1 is a invalid value");
}

// check empty value in `if...else` statement
if(str2){
  console.log("str2 is a valid value");
} else {
  console.log("str2 is a invalid value");
}

// check string value in `if...else` statement
if(str3){
  console.log("str3 is a valid value");
} else {
  console.log("str3 is a invalid value");
}

When you run the above program it should console a valid string for only the str1 variable.

let’s check the output.

javascript, check if a string is empty or undefined example
javascript, check if a string is empty or undefined example

I hope it’s help you, All the best 👍.