cyrus
cyrus

Reputation: 134

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{
}

Upvotes: 0

Views: 569

Answers (4)

p u
p u

Reputation: 1455

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{
}

Upvotes: 1

dhanu10896
dhanu10896

Reputation: 315

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

Upvotes: 1

Jay Raj Mishra
Jay Raj Mishra

Reputation: 140

var demo = "hello";

var flag = 0;

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

Upvotes: 0

ellipsis
ellipsis

Reputation: 12152

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{
}

Upvotes: 4

Related Questions