CodingTrain / Suggestion-Box

A repo to track ideas for topics
572 stars 86 forks source link

Video about destructuring in JS #969

Open cundamic opened 6 years ago

kleinesfilmroellchen commented 6 years ago

Could you provide a description?

Californ1a commented 6 years ago

Could you provide a description?

Destructuring lets you pull variables out of arrays or objects and name them in shorthand syntax.

// Not destructing
const a = [1, 2, 3];
let b = a[1];
console.log(b); // 2

// Destructuring
let [,b] = [1, 2, 3]; // Skip variables by adding the extra commas
console.log(b); // 2

// Destructuring (pull out multiple variables)
let [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3

Or with objects:

// Not destructing
const obj = {a:1, b:2, c:3};
let b = obj.b;
console.log(b); // 2

// Destructuring
let {b} = {a:1, b:2, c:3};
console.log(b); // 2

// Destructuring (multiple)
let {a, b:notB, c} = {a:1, b:2, c:3};
console.log(a, notB, c); // 1 2 3
// Note that `b` is undefined, it gets renamed to `notB`

Mozilla has a ton more examples with things like the ...rest operator, default values, more advanced iteration, assigning default values to objects passed into functions, etc. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment Some very handy stuff.