Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AND multiple parameters

function andMultipleExpr(){
  let logicalAnd;
  let i;
  for (i = 0; i < arguments.length; i++){
    logicalAnd =  arguments[i] && arguments[i+1];
  }
  return logicalAnd;
}

console.log(andMultipleExpr(true, true, false, false));

What I am expecting is to execute this code: true&&true&&false&&false and that should return false.

How to make that work in js? Thanks

like image 529
Hakim Asa Avatar asked Jan 15 '20 10:01

Hakim Asa


People also ask

What is multiple parameter?

Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.

Can functions have multiple parameters?

Luckily, you can write functions that take in more than one parameter by defining as many parameters as needed, for example: def function_name(data_1, data_2):


1 Answers

Use Array.prototype.every on all the passed arguments to check if they all are true;

function andMultipleExpr(...a) {
  if(a.length === 0) return false; // return false when no argument being passed
  return a.every(Boolean);
}

console.log(andMultipleExpr(true, true, false)); // should return false
console.log(andMultipleExpr(true, true, true)); // should return true
like image 191
Archie Avatar answered Sep 28 '22 05:09

Archie