Computer >> Computer tutorials >  >> Programming >> Javascript

How to check for null, undefined, or blank variables in JavaScript?


On getting the result of the following, you can find whether a variable is null or undefined. If the result is “false”, it means the variable is null and undefined.

Here, the variable results in “True” −

<html>
   <body>
      <script>
         var age = 10;
            if(age){
               document.write("True");
            } else{
               document.write("False");
            }
      </script>
   </body>
</html>

Use “typeof” to check whether a variable exists or not −

<html>
   <body>
      <script>
         var age = 10;
         if( typeof age !== 'undefined' ) {
            document.write("True");
         } else{
            document.write("False");
         }
      </script>
   </body>
</html>