Control Statements

  • 17.1 In case your control statement (if, while etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line.

    Why? Requiring operators at the beginning of the line keeps the operators aligned and follows a pattern similar to method chaining. This also improves readability by making it easier to visually follow complex logic.

    1. // bad
    2. if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) {
    3. thing1();
    4. }
    5. // bad
    6. if (foo === 123 &&
    7. bar === 'abc') {
    8. thing1();
    9. }
    10. // bad
    11. if (foo === 123
    12. && bar === 'abc') {
    13. thing1();
    14. }
    15. // bad
    16. if (
    17. foo === 123 &&
    18. bar === 'abc'
    19. ) {
    20. thing1();
    21. }
    22. // good
    23. if (
    24. foo === 123
    25. && bar === 'abc'
    26. ) {
    27. thing1();
    28. }
    29. // good
    30. if (
    31. (foo === 123 || bar === 'abc')
    32. && doesItLookGoodWhenItBecomesThatLong()
    33. && isThisReallyHappening()
    34. ) {
    35. thing1();
    36. }
    37. // good
    38. if (foo === 123 && bar === 'abc') {
    39. thing1();
    40. }

  • 17.2 Don’t use selection operators in place of control statements.

    1. // bad
    2. !isRunning && startRunning();
    3. // good
    4. if (!isRunning) {
    5. startRunning();
    6. }