javascriptarraysif-statementrest-parameters

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


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


Solution

  • 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;
        });
    }
    };