Skip to content

Instantly share code, notes, and snippets.

@BigAB
Last active June 28, 2016 18:10
Show Gist options
  • Save BigAB/dd138e258dcd42beb4df3aa62894a9a3 to your computer and use it in GitHub Desktop.
Save BigAB/dd138e258dcd42beb4df3aa62894a9a3 to your computer and use it in GitHub Desktop.
Arrow functions and code style

When deciding on which code style to use, under different circumstances (i.e. number of parameters, return value, etc.) a good solid rule for consistency and terseness is: Always use the minimum required syntax for the situation

The minimum does not include variable/parameter names, which should should be semantic to the meaning or general depending on how the function will be used. Using an unused parameter name to save one char (like _ => 2*2) is confusing and should be avoided.

With this rule in mind we end up with this:

// no params
() => {}                    // "noop" no parameters, no operations, no return value
() => value + 1             // no parameters, one line operation, a return value (that is not an object)
() => ({ foo: 'bar' })      // no parameters, one line operation, a object return value
() => {                     // no parameters, multi-line operation, a return value/object
  //...
  return value;
}

// one param
num => {}                   // "wtf" one parameter, no operations, no return value
num => num * num            // one parameter, one line operation, a return value (that is not an object)
text => ({ value: text })   // one parameter, one line operation, a object return value
items => {                  // one parameter, multi-line operation, a return value/object
  //...
  return newItems;
}

// multiple params
(item, collection) => {}       // "seriously wtf" multiple parameters, no operations, no return value
(n, col) => col.indexOf(n)     // multiple parameters, one line operation, a return value (that is not an object)
(val, type) => ({ type, val }) // multiple parameters, one line operation, a object return value
(items, comparetor) => {       // multiple parameters, multi-line operation, a return value/object
  //...
  return newItems;
}

This may look inconsistant at first glance, but is consistant when applied consistently and leads to easy to read/understand code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment