0

I am a JS beginner. Just read a couple of beginner books. I am now taking an online course and even though I thought I knew if statements this bit of code doesn't seem to run right.

Here is the simple code that is taken directly from the course teaching materials:

let stationery = "pen";
if (stationery == "pen" || "pencil") { 
    console.log("You have enough stationery to write the exam.");
}
else {
    console.log("You do not have sufficient stationery to write the exam.");
}

On the face of it it seems ok. When I see console.log the output say: You have enough stationery to write the exam.

However, if I change the stationery variable to something else like "chalk" and rerun the if statement, the console.log result still says: You have enough stationery to write the exam.

I would expect the final else statement to kick in and show: You do not have sufficient stationery to write the exam.

This is so early on in the course that I am almost embarrassed to ask. What am I missing? The beginner books I read were before let and used var. Is it anything to do with this that is confusing my beginner's understanding?

I think this could be something to do with "truthy" values in the if statement conditionals but I don't get it.

Thanks.

Bobby
  • 13
  • 3
  • 3
    your if statement is wrong. you check variable with every condition. try `if (stationery == "pen" || stationery == "pencil")` – Najam Us Saqib Jan 07 '23 at 15:43
  • either you repeat the variable name or use `includes` with an array `if( ["pen","pencil"].includes(stationery)` – Dickens A S Jan 07 '23 at 16:05

1 Answers1

1

Your conditional is wrong, it always will return a true value, because "pencil" is a truthy value, https://developer.mozilla.org/en-US/docs/Glossary/Truthy#:~:text=In%20JavaScript%2C%20a%20truthy%20value,type%20coercion%20in%20Boolean%20contexts.

let stationery = "pen";
if (stationery == "pen" || "pencil") { 
    console.log('this is always true')
}

Maybe this is the logic you are looking for:

let stationery = "pen";
if (stationery == "pen" || stationery ==  "pencil") { 
    // ...
}
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
  • Yikes. Thanks for your reply. I haven't learned things like "truthy" values yet. The course materials are wrong then. I will study this, but I have to say I'm now even more confused. – Bobby Jan 07 '23 at 16:01