Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 31, 2023 › #HowTo #Javascript

How to check if a variable is empty in JavaScript

Today I'm going to show you how to check if a variable is empty in JavaScript. In JavaScript, there are many ways to do this but among them, we will look at two or three ways.

it's too easy. You just need to understand the basics. So, let's see some examples.

Check if a variable is empty using length property. #

In the first example, we will use the length property to check if a variable is empty.

<script>
 const myVar="";
 if(myVar.length === 0){
   console.log("Variable is empty.");
 }else{
   console.log("Variable is not empty.")
 }
</script>

In the above example, we have defined the variable myVar and set it equal to an empty string.

Then, we used a condition statement in order to check whether or not our variable length is 0.

You can also use the typeof operator to check if a variable is empty, undefined or null. You can see the article: How to check if a variable is declared in JavaScript.

save
listen
AI Answer
Write Your Answer
loading
back
View All