Reputation: 537
I'm trying to write multiple logical operators in a more concise way. In my case, I want the function to only run when all four inputs are only numbers. The only way I can think of doing this is to write them all in one if statement with &&, use multiple ifs (as below), or use switch. But I was wondering if there is a more concise way.
function fn() {
const input = display.getInput();
if (input.p !== "" && !isNaN(input.p)) {
if (input.d !== "" && !isNaN(input.d)) {
if (input.s !== "" && !isNaN(input.s)) {
if (input.y !== "" && !isNaN(input.y)) {
if (input.y <= 100) {
/* run code */
}
}
}
}
}
}
Upvotes: 0
Views: 88
Reputation:
To answer exactly what you area asking, you could do it like this:
if (input.p !== "" && !isNaN(input.p) && input.d !== "" && !isNaN(input.d) ...
But in fact you should write it better. First implement a validation function:
function isValid(property) {
return property !== "" && !isNaN(property);
}
So the if would be like:
if (isValid(input.p) && isValid(input.d) && ...
And finally, you might want to put everything into a new function:
function isEverythingValid(input) {
for (let property of ["p", "d", "s", "y"]) {
if (!isValid(input[property])) {
return false;
}
}
return input.y <= 100;
}
Upvotes: 2