How using multiple conditions within an if statement?
function testNum(a) {
if (a == (1 || 2 || 3)) {
return "is 1, 2, or 3";
} else {
return "is not 1, 2, or 3";
}
}
console.log(testNum(1)); // returns "is 1, 2, or 3"
console.log(testNum(2)); // returns "is not 1, 2, or 3"
console.log(testNum(3)); // returns "is not 1, 2, or 3"
testNum(2) and testNum(3) should return: "is 1, 2 or 3" but doesn't.
In this particular scenario, you can even use an array and Array#includes method for checking.
if ([1, 2, 3].includes(a)) {
// your code
}
function testNum(a) {
if ([1, 2, 3].includes(a)) {
return "is 1, 2, or 3";
} else {
return "is not 1, 2, or 3";
}
}
console.log(testNum(1));
console.log(testNum(2));
console.log(testNum(4));
console.log(testNum(3));
(1 || 2 || 3) results 1(since 1 is truthy) and actually a == (1 || 2 || 3) does a == 1. The right way is to seperate each conditions with || (or), for eg : a == 1 || a == 2 || a ==3.
For more details visit MDN documentation of Logical operators.
You cannot have || like that. The one you have used is not the right way. You should be using:
function testNum(a) {
if (a == 1 || a == 2 || a == 3) {
return "is 1, 2, or 3";
} else {
return "is not 1, 2, or 3";
}
}
console.log(testNum(1));
console.log(testNum(2));
console.log(testNum(3));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With