Created
September 25, 2015 16:52
-
-
Save ksmithbaylor/ffa9158e9602796cd687 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Splitting out conditionals makes things more readable | |
const someCondition = (something.is == true) | |
// Ternary expressions are really useful for assigning values in an immutable | |
// way. This avoids setting `a` to something as a "default", and then | |
// conditionally setting it to something else. | |
const a = someCondition ? | |
oneThing : | |
anotherThing; | |
// Ternary expressions can be used for jsx too | |
const jsxSnippet = someCondition ? ( | |
<div> | |
<p>True option</p> | |
</div> | |
) : ( | |
<div> | |
<p>False option</p> | |
</div> | |
); | |
// With JSX, this technique is useful to include or disclude a component or | |
// other JSX snippet (if the condition is true, the component will be included. | |
// Otherwise, the whole thing will evaluate to false and not be included) | |
const inlineJsxToggle = ( | |
<div> | |
<SomeComponent /> | |
{someCondition && | |
<OptionalComponent /> | |
} | |
</div> | |
); | |
// Pure functions make immutable code easier to reason about | |
// A pure function takes only its arguments into account (no external conditions | |
// or data) and returns the same value every single time for the same set of | |
// arguments. A React component's `render` function can be though of as a pure | |
// function of its `props` and `state`. | |
function myFunc(a, b, c) { | |
return (a + b) * c; | |
} | |
// Pure functions tend to be a single `return` expression, so arrow functions | |
// express them very nicely | |
const myFunc = (a, b, c) => (a + b) * c; | |
// Map, filter, reduce, and friends make everything easier. MDN is a great | |
// resource for learning about these. | |
const input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
const onlyEvens = input.filter(x => (x % 2 === 0)); | |
const evenSquares = onlyEvens.map(x => x * x); | |
const sumOfEvenSquares = evenSquares.reduce((a, b) => a + b); | |
// I treat let and var assignments and for and while loops as code smells. | |
// I haven't found an instance yet where any of these are actually necessary. | |
// Keeping definitions 100% local to where they are assigned helps me reason | |
// about my code much more easily. | |
// There is a great utility library called `lodash` that helps you write | |
// functional-style code more easily in javascript. https://lodash.com/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment