Adi
Adi

Reputation: 4022

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 pulling 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.

Upvotes: -1

Views: 6356

Answers (5)

Sachin Shanbhag
Sachin Shanbhag

Reputation: 55519

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

Upvotes: 1

JohnP
JohnP

Reputation: 50029

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.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039368

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.

Upvotes: 1

Calum
Calum

Reputation: 5316

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.

Upvotes: 2

Pekka
Pekka

Reputation: 449763

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.

Upvotes: 8

Related Questions