Skip to content

Instantly share code, notes, and snippets.

@jnsprnw
Created April 5, 2018 09:46
Show Gist options
  • Save jnsprnw/1151f89cdbce76cca2b7f10e7a506dfb to your computer and use it in GitHub Desktop.
Save jnsprnw/1151f89cdbce76cca2b7f10e7a506dfb to your computer and use it in GitHub Desktop.
Rename & Destructure Variables in ES6

General

[a, b] = [1, 2]
[a, b, ...rest] = [1, 2, 3, 4, 5]
{ a, b } = { a: 1, b: 2 }
{ a, b, ...rest } = { a: 1, b: 2, c: 3, d: 4 }  // ES2016

Array destructuring

const foo = ['one', 'two', 'three']
const [one, two, three] = foo
// one = 'one', two = 'two', three = 'three'
let a, b
[a, b] = [1, 2]
// a = 1, b = 2
function f() {
  return [1, 2, 3]
}
const [a, , b] = f()
// a = 1, b = 3

Object destructuring

const o = { p: 42, q: true }

const { p, q } = o;
// p = 42, q = true

const { p: foo, q: bar } = o
// foo = 42, bar = true
function drawChart({ size: size = 'big', cords: cords = { x: 0, y: 0 }, radius: radius = 25 } = {}) {
  console.log(size, cords, radius)
}

drawChart({
  cords: { x: 18, y: 30 },
  radius: 30
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment