Skip to content
Advertisement

shorten if conditions in js

I want to shorten the conditions of a javascript if but I don’t know how I can achieve it

code:

    if ((!emailValidation() || (!nameValidation()) || (!surnameValidation()) || (!addressValidation()) || (!cityValidation()) || (!postalCodeValidation()))) {        
}

I have the conditions defined in this way:

let surnameValidation = () => {
    if (apellidoUsuario.value.length == 0) {
        surnameError();
        return false;
    }

    else if (apellidoUsuario.value.length == 1) {
        surnameError();
        return false;
    }

    else {
        apellidoUsuario.focus;
        apellidoUsuario.style.border = '0';
        apellidoUsuario.style.backgroundColor = 'transparent';
        apellidoUsuario.style.outline = '1px solid #00ffb1'
        apellidoUsuario.style.transitionDuration = '0.4s'
        return true;
    }

I appreciate any help! 🙂

Advertisement

Answer

You can remove all unnecessary parenthesis in your if condition:

if (
    !emailValidation() ||
    !nameValidation() ||
    !surnameValidation() ||
    !addressValidation() ||
    !cityValidation() ||
    !postalCodeValidation()
) {
}

Other than that, there’s not really a clean, readable way to shorten your code.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement