When doing the exercise on “If Statements,” I made a mistake at step 2 and typed if (true) initially, rather than if (sale). ‘Time to buy!’ appeared in the console, which didn’t surprise me as let sale = true.
After changing to sale = false, if (false) yields nothing in the console, of course. But if I type, if (true), ‘Time to buy!’ does appear in the console, even though the variable has been changed to false.
Please can someone explain why this is? I would think that if sale = false, if (true) would not yield anything in the console because there isn’t a variable that is true. (Just experimenting to see what happens off the back of my initial mistake!)
EDIT: I asked my friend and they said I created an “infinite loop” by not defining what it is that’s true. So I understand my mistake now on a simple level, but would still appreciate more detailed feedback if anyone wants to give it
It is late today and I am bit wrecked so thats probably why I read “a” as “o” in the code but having two different fonts for code and description is not helping.
I wondered why the code needs to be separately into different lines? Cant that 1 code exists on a single line?
I originally typed the code in 1 line and the result shows what is expected but didnt pass the exercise. Then i looked at the answer and is because we need to separate the code into 3 different lines.
Then I am setting the sale variable to false.
This also appears to work.
Finally, I am telling the program to print a message if sale is true.
And, the message prints.
If I look to see the value of the variable, it now says that it is true again…
Why? Why is the variable still seen as true, when I had set it to false most recently?
Screenshot included, and my code,
let sale = true;
console.log('first test' + '=' + sale);
sale = false;
console.log('second test' + '=' + sale);
if (sale = true) {
console.log('Time to buy!');
};
console.log('third test' + '=' + sale);
The condition given above is an assignment, not a comparison. The assignment does take place so the variable is now true. Because the condition didn’t ‘fire’ it was treated as a statement, followed by an anonymous code block that also executed.