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

How to check variable not undefined in JavaScript

Today I'm going to talk about how to check if a variable is not undefined in JavaScript. This is easy. You just need to understand the basics. So let's get started!

The first thing you need to do is create a variable and assign it some value. Suppose, you have a variable myVar that contains the value null.

Now we can use the comparison operator (==) or strict comparison (===). The == compares two values without considering their types while === considers both values types before comparing them.

<script>
 let myVar =  null;
  if(myVar == undefined){  
    console.log("myVar is undefined.");
  } else {
     console.log("myVar has some value.");
 } 
  // output => myVar is undefined.
</script>

Now, in the second example, let's try using === instead .

<script>
 let myVar =  null;
  if(myVar ===  undefined){  
    console.log("myVar is undefined.");
  } else {
     console.log("myVar has some value.");
 } 
  // output => myVar has some value.
</script>

In this tutorial, you have learned how to check if a variable is not undefined in JavaScript. I hope this was helpful for you guys! If there are any questions or comments feel free post below.

save
listen
AI Answer
Write Your Answer
loading
back
View All