Blocks

  • 16.1 Use braces with all multi-line blocks. eslint: nonblock-statement-body-position

    1. // bad
    2. if (test)
    3. return false;
    4. // good
    5. if (test) return false;
    6. // good
    7. if (test) {
    8. return false;
    9. }
    10. // bad
    11. function foo() { return false; }
    12. // good
    13. function bar() {
    14. return false;
    15. }

  • 16.2 If you’re using multi-line blocks with if and else, put else on the same line as your if block’s closing brace. eslint: brace-style

    1. // bad
    2. if (test) {
    3. thing1();
    4. thing2();
    5. }
    6. else {
    7. thing3();
    8. }
    9. // good
    10. if (test) {
    11. thing1();
    12. thing2();
    13. } else {
    14. thing3();
    15. }

  • 16.3 If an if block always executes a return statement, the subsequent else block is unnecessary. A return in an else if block following an if block that contains a return can be separated into multiple if blocks. eslint: no-else-return

    1. // bad
    2. function foo() {
    3. if (x) {
    4. return x;
    5. } else {
    6. return y;
    7. }
    8. }
    9. // bad
    10. function cats() {
    11. if (x) {
    12. return x;
    13. } else if (y) {
    14. return y;
    15. }
    16. }
    17. // bad
    18. function dogs() {
    19. if (x) {
    20. return x;
    21. } else {
    22. if (y) {
    23. return y;
    24. }
    25. }
    26. }
    27. // good
    28. function foo() {
    29. if (x) {
    30. return x;
    31. }
    32. return y;
    33. }
    34. // good
    35. function cats() {
    36. if (x) {
    37. return x;
    38. }
    39. if (y) {
    40. return y;
    41. }
    42. }
    43. // good
    44. function dogs(x) {
    45. if (x) {
    46. if (z) {
    47. return y;
    48. }
    49. } else {
    50. return z;
    51. }
    52. }