Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Boolean Gates in JavaScript
We are required to write a JavaScript function that takes in an array of Boolean values and a logical operator.
Our function should return a Boolean result based on sequentially applying the operator to the values in the array.
Problem
Given an array of Boolean values and a logical operator (AND, OR, XOR), we need to apply the operator sequentially to all values and return the final result.
Solution
Here's the implementation that handles three common Boolean operations:
const array = [true, true, false];
const op = 'AND';
function logicalCalc(array, op) {
var result = array[0];
for (var i = 1; i < array.length; i++) {
if (op == "AND") {
result = result && array[i];
}
if (op == "OR") {
result = result || array[i];
}
if (op == "XOR") {
result = result != array[i];
}
}
return result;
}
console.log(logicalCalc(array, op));
false
How It Works
The function starts with the first array element as the initial result, then iterates through remaining elements applying the specified operator:
- AND (&&): Returns true only if all values are true
- OR (||): Returns true if at least one value is true
- XOR (!=): Returns true if values are different (toggles result)
Examples with Different Operators
const testArray = [true, false, true];
console.log("AND:", logicalCalc(testArray, "AND"));
console.log("OR:", logicalCalc(testArray, "OR"));
console.log("XOR:", logicalCalc(testArray, "XOR"));
AND: false OR: true XOR: false
Improved Version with Switch Statement
function logicalCalcImproved(array, op) {
if (array.length === 0) return null;
let result = array[0];
for (let i = 1; i < array.length; i++) {
switch (op) {
case "AND":
result = result && array[i];
break;
case "OR":
result = result || array[i];
break;
case "XOR":
result = result !== array[i];
break;
default:
throw new Error("Invalid operator");
}
}
return result;
}
console.log(logicalCalcImproved([true, true, false], "AND"));
false
Conclusion
This function effectively implements Boolean gate logic by sequentially applying AND, OR, or XOR operations to array elements. The switch statement version provides better performance and error handling for production use.
