Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple conditions within an if statement

Tags:

javascript

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.

like image 724
Sky Red Tea Avatar asked Dec 13 '25 08:12

Sky Red Tea


2 Answers

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));

FYI : In your current code (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.

like image 100
Pranav C Balan Avatar answered Dec 16 '25 08:12

Pranav C Balan


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));
like image 27
Praveen Kumar Purushothaman Avatar answered Dec 16 '25 09:12

Praveen Kumar Purushothaman