Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 function parameter validation

I've read a great pattern of handling required function parameters on 2ality.

function throwIfMissing() {
    throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
    return mustBeProvided;
}

Is there any such nice and clean way to throw validation errors?

function throwIfInvalid(value) {
    const max = 10;
    const min = 5;

    if(value < min || value > max){
        throw new Error(`Value must be between ${min} ${max}`);
    }

    return value;
}

function foo(mustBeValid = throwIfInvalid()) {
    return mustBeValid;
}

Of course the throwIfInvalid() function does not work as expected. My question is if there is any trick to make it work.?

like image 748
Adam Avatar asked Mar 07 '26 13:03

Adam


1 Answers

Of course it doesnt work, i think you are misunderstanding how Default Parameters work.

When you write

function foo(mustBeProvided = throwIfMissing())

you are assigning the result of throwIfMissing to the parameter IF AND ONLY IF the parameter is undefined.

Meaning that if that parameter is provided then throwIfMissing is not called at all; it will never execute and will never check for the validity of your parameter.

That's why you can only use this "trick" to react to an undefined parameter, not to validate one.

--

Alternative Solution

Personally i would solve the problem with a simple solution

function checkRange(val, min, max) {
    if (val > max || val < min) {
        throw new Error();
    }
}

function foo(val) {
    checkRange(val, 5, 10);
    return val;
} 

You may argue that this is much less elegant but keep in mind that in this case you can reuse the validator with different values, you don't have to hardcode min and max.

If you are looking for an npm module you can try this one but i wouldn't go that far for a simple validation.

like image 100
Bolza Avatar answered Mar 09 '26 01:03

Bolza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!