Skip to content

Commit

Permalink
Add ES2015 destructuring sample
Browse files Browse the repository at this point in the history
  • Loading branch information
addyosmani committed Jan 26, 2016
1 parent 18603fa commit dc64f83
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
5 changes: 5 additions & 0 deletions destructuring-es6/README.md
@@ -0,0 +1,5 @@
Destructuring (ES2015) Sample
==================================
See https://googlechrome.github.io/samples/destructuring-es6/index.html for a live demo.

Learn more at https://www.chromestatus.com/feature/4588790303686656
39 changes: 39 additions & 0 deletions destructuring-es6/demo.js
@@ -0,0 +1,39 @@
// ES2015 destructuring assignment lets you extract data from arrays or objects
// using a syntax similar to the construction of array and object literals
var cats = ['😹', '🙀', '😻'];
var catAges = {sam: 12, passy: 14, surma: 16};

// Access the first three items of an array in ES5
var one = cats[0];
var two = cats[1];
var three = cats[2];
ChromeSamples.log(one, two, three);

// Destructure the array in ES2015
var [a, b, c] = cats;
ChromeSamples.log(a, b, c);

// Destructure an array omitting certain values
var [x, , y] = cats;
ChromeSamples.log(x, y);

// Destructure an array using the ES2015 rest operator
var [kitty, ...otherKitties] = cats;
ChromeSamples.log(kitty, otherKitties);

// Destructure an object
var {passy, surma} = catAges;
ChromeSamples.log(passy, surma);

// Destructure an object, binding variables to different properties
var {sam: cat1, passy: cat2, surma: cat3} = catAges;
ChromeSamples.log(cat1, cat2, cat3);

// Default values for function object parameters
var request = ({
url: url = 'github.com', crossDomain: crossDomain = true},
...data) => {
ChromeSamples.log(`url: ${url}, crossDomain: ${crossDomain}, data: ${data}`);
};

request({url: 'thecatapi.com'}, 'cute', 'kittens');
14 changes: 14 additions & 0 deletions destructuring-es6/index.html
@@ -0,0 +1,14 @@
---
feature_name: Destructuring (ES2015)
chrome_version: 49
feature_id: 4588790303686656
---

<h3>Background</h3>
<p><a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment'>Destructuring assignment</a> allows extracting data from arrays or objects using a syntax that mirrors array and object literals.</p>

<p>The object and array literal expressions provide an easy way to create ad hoc packages of data. Once you've created these packages of data, you can use them any way you want to. You can even return them from functions.</p>

{% include output_helper.html %}

{% include js_snippet.html filename='demo.js' %}

0 comments on commit dc64f83

Please sign in to comment.