How to check if a variable is empty in JavaScript

                                                        

   On - 12 Feb, 2023
   By - Apu Gorai
Check if the variable is un.defined: typeof variable === 'un.defined'
<script>
 let myVar;
 if(typeof myVar === 'un.defined') {
    console.log('Yes') // output 'Yes'
  }else{
    console.log('No')
  }
</script>
Check if the variable is null: variable === null
<script>
 let myVar;
 if(myVar == null) {
    console.log('Yes') // output 'Yes'
  }else{
    console.log('No')
  }
</script>
Check if the variable is an empty string: variable === ""
<script>
 let myVar = '';
 if(myVar === '') {
    console.log('Yes') // output 'Yes'
  }else{
    console.log('No')
  }
</script>
Check if the variable is an empty array: variable.length === 0
<script>
 let myVar = [2,3];
 if(myVar.length === 0) {
    console.log('Yes')
  }else{
    console.log('No') //output 'No'
  }
</script>
Check if the variable is an empty object: Object.keys(variable).length === 0
<script>
 let myVar = {};
 if(Object.keys(myVar).length === 0) {
    console.log('Yes') // output 'Yes'
  }else{
    console.log('No')
  }
</script>

  Check if the variable is a false boolean: variable === false 

<script>
 let myVar = true;
 if(myVar === false) {
    console.log('Yes')
  }else{
    console.log('No') // output 'No'
  }
</script>
Check if the variable is NaN: Number.isNaN(variable)
<script>
 let myVar = '8';
 if(Number.isNaN(myVar)) {
    console.log('Yes')
  }else{
    console.log('No') // output 'No'
  }
</script>
Load More »