From ed2da5c8aba833de8946bf71f2996b59607bba90 Mon Sep 17 00:00:00 2001 From: Josh Black Date: Mon, 16 Dec 2019 16:18:43 -0600 Subject: [PATCH] docs(style): add style preference for writing code explicitly (#4879) * docs(style): add style preference for explicit features * docs(style): update phrasing * docs(style): add explicit table example for section * docs(style): move table block to beginning of section --- docs/style.md | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/docs/style.md b/docs/style.md index 32b8bcef2b00..e62f0bcdc396 100644 --- a/docs/style.md +++ b/docs/style.md @@ -60,6 +60,9 @@ row before the line. ## Table of Contents - [Introduction](#introduction) +- [JavaScript](#javascript) + - [Style](#style) + - [Be explicit](#be-explicit) - [React](#react) - [Guidelines](#guidelines) - [Writing a component](#writing-a-component) @@ -90,6 +93,69 @@ code: _Inspired by [Minimal API Surface Area](https://www.youtube.com/watch?v=4anAwXYqLG8)_ +## JavaScript + +### Style + +#### Be explicit + + + + + +
UnpreferredPreferred
+ +```jsx +const add = (a, b) => a + b; +``` + + + +```jsx +const add = (a, b) => { + return a + b; +}; +``` + +
+ +Certain features in JavaScript have implicit behavior. One of these that we see +most often is the implicit return behavior of arrow function expressions, for +example: + +```js +const add = (a, b) => a + b; +``` + +We've found that, while this style is terse and compact, it can be at odds with +the fact that code is revisited often and that developers need to peak inside +sometimes to see what is going on. For example, if we needed to debug a specific +value in the function above then we would go through the following steps: + +```js +// Step 1. The code as originally authored +const add = (a, b) => a + b; + +// Step 2. Update the code to no longer use the implicit return +const add = (a, b) => { + return a + b; +}; + +// Step 3. Add any debugging code or ways to introspect its values +const add = (a, b) => { + console.log(a); + return a + b; +}; + +// Step 4. Undo these changes and bring back to original format +const add = (a, b) => a + b; +``` + +If instead we had written this code without the implicit return then we would +have saved three out of the four steps above. As a result, we tend to favor +being explicit in how JavaScript is written instead of relying on implicit +behavior. + ## React ### Guidelines