mardi 29 août 2017

Is it stylistically acceptable to omit the 'else' when returning within a javascript function? [on hold]

When writing a javascript function, I commonly need to check if an error has been thrown before returning. I might have something like this:

() => {
    let error = false
    // do some stuff, perhaps making error=something if an error is found
    if (error) { 
        return error
    } else {
        //carry on with the function
    }
}

However, I would much rather write something like

() => {
    let error = false
    // do some stuff...
    if (error) {return error}
    // carry on with the function...
}

There is no explicit 'else', but the function will return and stop in the presence of an error, and the code looks neater and has less indentation. But I feel like this might violate some important stylistic principle - when and 'if' has an alternative path based on its failure, that should always go in an 'else'.

Am I worrying over nothing, or should I stick with the first style?

Aucun commentaire:

Enregistrer un commentaire