How to check if a variable is declared in JavaScript

Question: I use this to check if variable exists,but it's not work.

  if(variable  !== undefined) // it don't work

Error: Uncaught ReferenceError: myvar is not defined

Answer: Two point we should know: In javascript, null is an object, A variable could be with name you can not to use null to check if variable exists, but check if initialized.

  console.log(yourvar); //undefined
  console.log(typeof null); //object
  console.log (yourvar == null) //false
  console.log (yourvar === null) // false
  if (yourvar !== undefined){ // Does not execute if yourvar is with name undefined
  var myvar = null
  console.log(typeof myvar === 'undefined')//false
  if (typeof yourvar === 'undefined'){
    // Does not execute if yourvar is null 
  if (typeof yourvar === 'undefined' || yourvar===null){
        // solution
  if (typeof yourvar !== 'undefined'){ 
      // solution
date2019-04-12 10:46:48 Author:JPH
Related Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *