How to specify multiple conditions in an array and call it in an if statement in javascript

590 views Asked by At

I don't know this can be possible or not I want to store all my condition in array and need to call it in if statement

const addition = (...numbers) => {

    let arrayOfTest = [
        `${numbers.length === 0}`,
        `${numbers.some(isNaN)}`,
        `${numbers === null}`,
    ];

    if (arrayOfTest.includes(true)) {
        throw new Error("Invalid Input");
    } else {
        return numbers.reduce((a, b) => {
            return a + b;
        });
    }
};

console.log( addition(1, 3, 4, 5, 7, 8));

Is this possible? Can I write all my conditions in array list and call it in if statement

1

There are 1 answers

2
Unmitigated On BEST ANSWER

Don't enclose the boolean values in backticks, as that makes them strings.

const addition = (...numbers) => {

let arrayOfTest = [
    numbers.length === 0,
    numbers.some(isNaN),
    numbers === null,
];
if (arrayOfTest.includes(true)) {
    throw new Error("Invalid Input");
} else {
    return numbers.reduce((a, b) => {
        return a + b;
    });
}
};