简体   繁体   中英

Not able to call global variable in nested if statement in javaScript

Can i anyone help right now i am not able to call a variable define in global inside a nested if demo code is given below ps: here it is working but in my actual code at this place i am getting problem

 var demo = "hello"; var flag ="0"; if( flag == "0"){ console.log('sucess' + demo); // i am getting this value if(flag == "0"){ console.log(demo); // not able to access here } else { }; } else{ } 

Use var flag="0" not var flag=="0" .Its assignment not comparison. Values are assigned using single = operator while comparison uses == or === operators to compare values. Both aren't the same.

 var demo = "hello"; var flag ="0"; if( flag == "0"){ console.log('sucess' + demo); // i am getting this value if(flag == "0"){ console.log(demo); // not able to access here } else { }; } else{ } 

Don't know how you get hello in the first place because you've used "==" which is used for comparison and "=" used for assignment of a variable.

 var demo = "hello"; var flag ="0"; //now the value is assinged with help of "=" if( flag == "0"){ // compare value of flag with 0 with help of "==" console.log('sucess' + demo); // i am getting this value if(flag == "0"){ console.log(demo); // not able to access here } else { }; } else{ } 

change var flag == "0"; to var flag = "0";

var demo = "hello";

var flag = 0;

if( flag === 0){
  console.log("sucess" + demo); 
  if(flag === 0){
    console.log(demo); 
  }
  else { }
}
else{ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM