0
Pls can anyone explain to me why the (else if) condition is not working in the code below even when it's condition is meat???
I want to understand why the (else if) statement is not executed when (buy =false) i. E assigned false. var buy = prompt("place your order","order"); x= buy; if(buy=true){alert("thanks for ordering a " + x);} else if(buy=false){alert("thanks for wasting DATA on our site");} else {alert("");}
3 Réponses
+ 10
You need to use == for comparisons. Single = is used to assign a value to a variable. So in the if, you're assigning true to buy, and since buy is true, the if runs and the else if is ignored.
if (buy == true)
{
}
else if (buy == false)
{
}
else
{
}
+ 3
Firstly, = is not a comparison. Use == to compare a condition.
x = buy; doesn't make sense. What is x?
Fix:
var x = buy;
Even this isn't neccessary though, you can just use buy.
Also, for booleans comparing a condition is redundant.
Just write: if(buy).
However, prompt doesn't return you a boolean it returns you what the user enters. If the user clicks cancel it returns null.
So:
if(buy != null)
{
// user entered something
}
Info on prompt:
https://www.w3schools.com/jsref/met_win_prompt.asp
+ 3
x=buy?