Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Javascript Check If a Variable is Undefined or Null</title> </head> <body> <p><strong>Note:</strong> Press <b>F12</b> key on the keyboard and click on the "console" tab to view the console output. Refresh the page or click the "Show Output" button to run the test again.</p> <hr> <script> var firstName; var lastName = null; // Try to get non existing DOM element var comment = document.getElementById('comment'); console.log(firstName); // Print: undefined console.log(lastName); // Print: null console.log(comment); // Print: null console.log(typeof firstName); // Print: undefined console.log(typeof lastName); // Print: object console.log(typeof comment); // Print: object console.log(null == undefined) // Print: true console.log(null === undefined) // Print: false /* Since null == undefined is true, the following statements will catch both null and undefined */ if(firstName == null){ document.write('<p>Variable "firstName" is undefined.</p>'); } if(lastName == null){ document.write('<p>Variable "lastName" is null.</p>'); } /* Since null === undefined is false, the following statements will catch only null or undefined */ if(comment === undefined) { document.write('<p>Variable "comment" is undefined.</p>'); } else if(comment === null){ document.write('<p>Variable "comment" is null.</p>'); } </script> </body>