Hey there, fresh coder, no experience before this course. I was doing a final review from the conditional statements course when I started playing around with conditionals to make sure I learnt them. This lesson:
Anyways, I hit a funny quirk with my code. Here it is…
let magic = 'poison cloud';
if (magic === 'frostbolt' || 'fireball' || 'arcane blast') {
console.log('Deals thermal damage');
} else if (magic === 'earth shock') {
console.log('Deals blunt damage');
} else if (magic === 'poison cloud') {
console.log('Deals biological damage');
} else {
console.log('Not a valid spell!');
}
The idea is by changing the ‘magic’ variable, I get a printout based on what its value is. I thought I’d consolidate the code by using the OR statement “||” for spells that deal the same kind of damage, IE if the magic variable is set to frostbolt OR fireball OR arcane blast, it deals thermal damage. Currently, the input is set to ‘poison cloud’, and so it should print out ‘deals biological damage’, but instead it prints out ‘deals thermal damage’ as if it was a frostbolt, fireball, or arcane blast, despite not being any of them!
Baffled, I played with the script a bit, and I discovered it works when I switch “||” to “&&”. By turning the second line to “if (magic === frostbolt && fireball && arcane blast);” , it suddenly works, and inputting ‘poison cloud’ correctly prints the right message! Not only that, but when I input ‘frostbolt’, it correctly reverts back to thermal damage as it’s supposed to, despite ‘frostbolt’ not being equal to ‘fireball AND frostbolt AND arcane blast’.
An && statement should only work if all parts of it are ‘true’, so why does it return ‘true’ when only one of its parts matches? And why is an || statement returning as ‘true’ when none of its parts match?
It worked when I used “&&” instead of “||”, but I have no idea why, and I’d like some insight into why it works this way, or else I feel like I might get issues further down the road. Again, fresh coder, near-zero experience, and even some of the vocab is real new to me, so please be gentle.