simple javascript if not working
I'm new to javascript and am having issues with a seemingly simple if/else statement.
Can anyone let me know why the below isn't working please (Im pul开发者_开发知识库ling my hair out)
var is_expanded = false;
if (is_expanded==false) {
alert('no');
is_expanded = true;
} else {
alert('yes');
}
I always get the 'no' alert (I never get to the else part).
Cheers for any help.
This is working as designed.
The condition is checked when you say if
. It then goes into the correct block, in this case the one that alerts "no".
The condition does not get re-evaluated after the block has been executed. That's just not how the if
statement works, not in any language I know.
Depending on what you want to do, there are other patterns and constructs that can help you, for example a while
loop. Maybe show the real use case that you need this for.
That's because is_expanded
always equals false
because you've set it as false
BEFORE the if statement.
else will not fire unless is_expanded
equals true
before the if statement.
You previous line of code says var is_expanded = false;
which means if (is_expanded==false)
will always evaluate to true
.
So that is exactly what you are getting as output. What did you expect?
Next time when your same method is called, the value for is_expanded
is again reset to false
due to your first line of code. Then again it will alert no
That's normal. You have set the variable is_expanded
to false
so in the if statement you are always entering the alert('no');
part. After you set the variable to true but there is no longer any if statement executed.
var is_expanded = false;
if (is_expanded==false) {
alert('no');
is_expanded = true;
} else {
alert('yes');
}
Congratulations! Your code is working perfectly, so stop pulling your hair out.
The nature of IF/ELSE is that only one of them fires per pass. So, your code checks whether is_expanded
is FALSE. If it's false, it will run the IF part. If not, it'll run the ELSE part.
Just read it like english.
If something, do this. Otherwise, do something else
Even if you change the value of the variable inside one of the blocks, it won't matter because once it checks the block, it moves on.
精彩评论