Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Determine If a Variable Exists in JavaScript</title> </head> <body> <p><strong>Note:</strong> Press F12 key on the keyboard and see the console tab for errors. Click the "Show Output" button or refresh the page to run the test again.</p> <hr> <script> var x; var y = 10; if(typeof x !== 'undefined'){ // this statement will not execute document.write("Variable x is defined."); } if(typeof y !== 'undefined'){ // this statement will execute document.write("Variable y is defined."); } // Attempt to access an undeclared z variable if(typeof z !== 'undefined'){ // this statement will not execute document.write("Variable z is defined."); } /* Throws Uncaught ReferenceError: z is not defined, and halt the execution of the script */ if(z !== 'undefined'){ // this statement will not execute document.write("Variable z is defined."); } /* If the following statement runs, it will also throw the Uncaught ReferenceError: z is not defined */ if(z){ // this statement will not execute document.write("Variable z is defined."); } </script> </body> </html>