Implement and, or logical function in JavaScript

June 21, 2020

||(OR)

In ||, If any of its arguments are true, it returns true, otherwise it returns false.You will write a function that will return true if any one of the params passed is evaluated to true, otherwise returns false.

function or(...tests) {
    let length = tests.length;
  for (let i = 0; i < length; i++) {
    if (tests[i]) { // if any one of the param is true , return true
        return true;
    }
  }
  return false;
}

or(); // false
or(false); //false
or(true); //true
or(true, false); // true
or("", false); // false

&&(AND)

In &&, If any of its arguments are false, it returns false, if all the elements are true then returns true. You will write a function that will return true if all of the params passed is evaluated to true, otherwise returns false.

function and(...tests) {
    let length = tests.length;
    for (let i = 0; i < length; i++) {
        if (!tests[i]) { // if any one of the param is true , return true
            return false;
        }
    }
    return !!length; // if 0 length then !!0 -> false , otherwise returns true
}

and(); // false
and(1); //false
and(true); //true
and(true, false); // false
and(true, true); // true

Please donate here, for making more tutorials.