Hi Everyone,
I know the following code isn’t considered ‘best form’ in Javascript (although I seem to remember that in Java it was okay). Anyway, can someone tell me what is going on here? Notice that I put a console.log statement inside the ‘if’ statement to help debug. To my befuddlement, when I select ‘Monday’ on the dropdown menu, the console.log evaluates to true, but the code in the ‘if’ statement still runs (i.e. I still get the message that it is the weekend and to stay home).
Any idea on why this is happening? Thanks.
onEvent(“dropdown1”, “change”, function( ) {
if (getText(“dropdown1”)==“Saturday”||“Sunday”) {
console.log(getText(“dropdown1”)==“Monday”);
setText(“msg_label”, “It’s the weekend! Stay home!”);
} else {
setText(“msg_label”, “It’s a weekday. Go to school.”);
}
});
It’s a syntax error on line 4. We would say “if the dropdown equals Saturday or Sunday” because that’s the way we speak. The computer doesn’t think that way. It needs a boolean on either side of the comparison operator.
I copy/pasted your code (I took out line 5) and took a video to show the difference. With your original code ALL days return the weekend code.
Also for future reference, it helps us troubleshoot code if you can use the “Share” button and post a direct link to your project so people can run the code and make a copy more easily to play around with it if needed.
Thank you so much for taking the time to reply! I watched the video you made (awesome), but if you can offer insight as to why the conditional statement is even evaluating to true in the first place, that would be great.
If there is a syntax error, shouldn’t the code just not run? Instead, it’s running for every choice of the day of the week.
I would try running it with this as the conditional: if (“Sunday”)
My guess is for some reason that always evaluates to “true” (or referencing the reading @kaitie_o_bryan posted, it would be a “truthy” statement).
You current “if” statement if (getText(“dropdown1”)==“Saturday”||“Sunday”)
is basically saying
“IF the dropdown equals ‘Saturday’… OR… IF ‘Sunday’”
The conditional “IF ‘Sunday’” makes no sense, but that’s what you’re asking the computer to evaluate. Since you say your program evaluates true in all cases, the computer must be evaluating that statement as true all the time.
According to that same reading, any string on its own is a truthy statement. (There’s a line for “some string”)
Frank and @kaitie_o_bryan, thank you for your thoughtful replies. I had never heard of this idea of ‘truthy’ and ‘falsey’ in programming until you mentioned it. (Sounds like words that Michael Scott would have made up). I looked at the app Kaitie suggested and I also tried if (“Sunday”) as Frank suggested to see what ‘truthy’ is all about. Although I don’t know why Javascript was developed this way, at least I have an answer for a kid if they ever explore a little more like I did.