I was just wondering, is there a shortcut for logical operator(&&
, ||
). Like if I want to do something like i = i + 10
, I can do i += 10
Reason I'm searching this is because I have a validation function which is divided into several functions. Following is a simulation:
function f1(){
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function f2(){
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function f3(){
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function f4(){
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function validate(){
var valid = true;
valid = valid && f1();
valid = valid && f2();
valid = valid && f3();
valid = valid && f4();
console.log(valid);
}
validate();
I have tried &=
function f1(){
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function f2(){
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function f3(){
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function f4(){
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function validate(){
var valid = true;
valid &= f1();
valid &= f2();
valid &= f3();
valid &= f4();
console.log(valid);
}
validate();
Now this can works, since true & false = 0
and 0
is false, but this looks more like a hack and was wondering if there is a better way to do such task?
Note:
I have tried valid = f1() && f2() && f3 && f4();
, but in this approach, if any function returns false
, subsequent functions are not executed.
Edit 1 - Nina's Suggestion
function f1(){
console.log("f1");
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function f2(){
console.log("f2");
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function f3(){
console.log("f3");
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function f4(){
console.log("f4");
return Math.ceil(Math.random()*10) %2 === 0? true:false
}
function validate(){
var valid = true;
var validateFuncList = [f1,f2,f3,f4];
valid = validateFuncList.every(function (f) { return f(); });
console.log(valid);
}
validate();
Now this is a great answer, but this stops if any one returns false
, which is same as valid = f1() && f2() && f3 && f4();
Edit 1
Just a minor update. Instead of doing: valid = valid && func1()
do valid = func1() && valid
. First approach will not call func1
if valid is false
.
Validate them all at once to make it shorter.
Basically you only check the next
f
function if the previous is true, that's the same that you do in your code, except it doesn't continue if it doesn't need to (if one of the previous is false).See: JavaScript Comparison and Logical Operators
Maybe you use an array. It calls all functions.
or with an array as parameter
Here's another approach which is much more concise. Bitwise-and doesn't short-circuit, so all functions will execute.
Of course
&
is bitwise-and, not logical-and, but as long as your functions return booleans this makes no difference. At the end you can cast to boolean using!!
if this is important.