Skip to content

Instantly share code, notes, and snippets.

@Jezfx
Last active October 23, 2017 16:14
Show Gist options
  • Save Jezfx/13f745b7d525b3b118d351fb497b1242 to your computer and use it in GitHub Desktop.
Save Jezfx/13f745b7d525b3b118d351fb497b1242 to your computer and use it in GitHub Desktop.
hotshot ES6 snippets πŸ”₯ (js)

1) Find an index

Get a single post from an array of objects

const i = this.props.posts.findIndex((post) => post.code === postId);
const post = this.props.posts[i];

2) Switch two variables around

Use destructuring to re-assign two variables

let foo = 'foo';
let bar = 'bar';

[foo, bar] = [bar, foo]

console.log(`foo: ${foo} - bar: ${bar}`); // foo: bar - bar: foo

3) Function short hand

Short hand to use a normal ES5 function inside an object. Which you'd want to do when not wanting to bind this to block (arrow function)

const foo = {
  bar: 'foo',
  foo() {
    console.log(this.bar)
  }
}

4) Destructurings

a) Destructuring the values returned from a function

const { foo, bar } = functionName(100)

b) Destructuring the params of a function which makes each param optional not dependant on the order

function tipCalc({ total = 100, tip = 0.15, tax = 0.13 } = {}) {
  return total + (tip * total) + (tax * total);
}

const bill = tipCalc({ tip: 0.20, total: 200 });
console.log(bill);

5) Spreading

Merge arrays

const featured = ['Deep Dish', 'Pepperoni', 'Hawaiian'];
const specialty = ['Meatzza', 'Spicy Mama', 'Margherita'];

const pizzas = [...featured, 'veg', ...specialty];
const fridayPizzas = [...pizzas];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment