DEV Community

Discussion on: If/else or just if?

Collapse
 
coachmatt_io profile image
Matt

I don't prefer one over the other, but what I do prefer is a single return statement, so you can make more assumptions about the code (eg: should get to the end of the function if there's no error)

let result

if (typeof val === 'string') {
    result = 'A'
} else if (val === null || val === undefined) {
    result = 'B'
} else {
    result = val
}

return result
Collapse
 
maixuanhan profile image
Han Mai

IMO, the single return comes from C coding guidelines where it may help developers easier to trace the complex code and prevent them from forgetting release any resources which need finalizing (like freeing heap). For this point, C++ projects usually don't adopt this guideline since it has its own stack-unwinding thing.

For Javascript, I prefer the statement B for more readable code. Save everyone's effort.

Collapse
 
fhusquinet profile image
Florian Husquinet

I find it more confusing to return a variable in a return unless it is really basic (like changing the message of a JSON response depending the data given).

Early returns make it sure you don't even up with mutating the response somewhere later in the code. It also make more readable (imo) because not everything is nested.

Collapse
 
simbo1905 profile image
Simon Massey

A lot of people would recommend using const by default. A variable that can be many things is cognitive overhead and results in bugs down the line.