|
// Spread Operator |
|
// --------------- |
|
// an in-place expansion of an expression |
|
|
|
//arrays can now be concatenated with ease: |
|
let cde = ['c', 'd', 'e']; |
|
let scale = ['a', 'b', ...cde, 'f', 'g']; // ['a', 'b', 'c', 'd', 'e', 'f', 'g'] |
|
|
|
// object literals can be concatenated: |
|
let mapABC = { a: 5, b: 6, c: 3}; |
|
let mapABCD = { ...mapABC, d: 7}; // { a: 5, b: 6, c: 3, d: 7 } |
|
|
|
// spread operator in a function call |
|
const add = (a, b) => a + b; |
|
let args = [3, 5]; |
|
add(...args); // same as `add(args[0], args[1])`, or `add.apply(null, args)` |
|
|
|
|
|
// Rest arguments (in a function call) |
|
// ----------------------------------- |
|
// Rest arguments are used to access a variable number of arguments passed to a function. |
|
// it collects an indefinite number of comma separated expressions into an array |
|
|
|
function add(...numbers) { |
|
return numbers[0] + numbers[1]; |
|
} |
|
|
|
add(3, 2); // 5 |
|
|
|
// or in es6 style: |
|
const addEs6 = (...numbers) => numbers.reduce((p, c) => p + c, 0); |
|
|
|
addEs6(1, 2, 3); // 6 |
|
|
|
// accessing rest arguments and/or arguments |
|
function print(a, b, c, ...more) { |
|
console.log(more[0]); |
|
console.log(arguments[0]); |
|
} |
|
|
|
print(1, 2, 3, 4, 5); |
|
// 4 |
|
// 1 |
|
|
|
|
|
// Destructuring |
|
// -------------- |
|
// Destructuring is a way to quickly extract data out of an {} or [] |
|
|
|
// with array [] |
|
let foo = ['one', 'two', 'three']; |
|
let [one, two, three] = foo; |
|
console.log(one); // 'one' |
|
|
|
// with json object {} |
|
let myModule = { |
|
drawSquare: function drawSquare(length) { /* implementation */ }, |
|
drawCircle: function drawCircle(radius) { /* implementation */ }, |
|
drawText: function drawText(text) { /* implementation */ }, |
|
}; |
|
|
|
let {drawSquare, drawText} = myModule; |
|
|
|
drawSquare(5); |
|
drawText('hello'); |
|
|
|
// with objects arguments in a function (destructured arguments) |
|
// Destructuring can also be used for passing objects into a function |
|
|
|
let jane = { firstName: 'Jane', lastName: 'Doe'}; |
|
let john = { firstName: 'John', lastName: 'Doe', middleName: 'Smith' } |
|
function sayName({firstName, lastName, middleName = 'N/A'}) { |
|
console.log(`Hello ${firstName} ${middleName} ${lastName}`) |
|
} |
|
|
|
sayName(jane) // -> Hello Jane N/A Doe |
|
sayName(john) // -> Helo John Smith Doe |
|
|
|
|
|
|
|
|
|
|
|
|
|
|