John Pizzo John Pizzo - 4 months ago 5
Javascript Question

What is the downside of using one-line if statements?

I see most code-bases using bracketed if-statements in all cases including cases in which only one statement needs to be executed after the if.

Are there any clear benefits to always using bracketed if-statements or has it just become a standard over time?

What is the general consensus on this, would it be a big mistake to allow one-line ifs through our linter?

Answer

Largely this comes down to developer preference, although many reasons are given for using the curly braces on every control block.

First, it makes the control block more readable. Consider:

    if (some_condition)
runSomeFunction();
        runSomeOtherFunction();

Since indentation is not respected in most curly brace languages, this will work, but it really reduces the readability (only runSomeFunction() will happen in the control block). Compare to:

if (some_condition) {
    runSomeFunction();
}
runSomeOtherFunction();

Second, when you need to add something to the control block (which almost invariably happens more often than not), adding the curly's can be frustrating or easily forgotten leading to issues like the above.

Still, those largely come down to preference and you can always find exceptions (like if (some_condition) runSomeFunction(); which is much more readable than the first example above while still accomplishing the same goal in a much more concise format that retains readability).

Comments