ES6 of the Week

This Week's Episode:

rest, spread, and function defaults

Parameter defaults

// maybe you've seen... 
function foo (a, b) {
    b = b || 'bar';
    return a + b;
}

function foo (a, b) {
    if (b === undefined) b = 'bar';
    return a + b;
}

now we don't need to include default values as part of the function logic!

// the ES6 way!
function foo (a, b='bar') {
    return a + b
}

Rest Parameter

  • allows us to represent an indefinite number of arguments as an array

  • aggregates the remaining arguments into a single parameter (helpful for variadic functions!)

function(a, b, ...theArgs) {
  // ...
}

Rest parameter

function foo (a, ...args) {
    // much easier and more descriptive than Array.prototype.slice.call!
    args.forEach(arg => {
        console.log(a * arg);
    });
}

foo(2, 1, 2, 3, 4, 5)        // => 2, 4, 6, 8, 10

Arguments Obj

  • only refers to arguments that haven't been given an explicit name
  • contains ALL arguments passed to the function
  • is not a real array (an array-like object)
  • has additional functionality specific to itself (ie callee, caller methods)
  • is an array instance (aka you can use methods like sort, map, forEach or pop)

Rest Params

Rest parameter

//using array methods on the rest parameters
function sortRestArgs(...theArgs) {
  var sortedArgs = theArgs.sort();
  return sortedArgs;
}

console.log(sortRestArgs(5,3,7,1)); // => 1,3,5,7

Using the Spread Operator

  • The spread syntax allows an expression to be expanded in places where...

    • multiple arguments (for function calls) or

    • multiple elements (for array literals) or

    • multiple variables  (for destructuring assignment)

are expected.

Spreading the love

function foo (a, b, c) {
    console.log(a);
    console.log(b);
    console.log(c);
}

let arr = [1, 2, 3];

// we could use Function.prototype.apply... 
foo.apply(null, arr);

// or we could use spread
foo(...arr);


Spreading the love

let numbers = [1, 2, 3];
let letters = ['a', 'b', 'c'];

// we could use Array.prototype.concat...
// but if we use the spread operator we can easily declaratively flatten arrays
let both = [...numbers, ...letters]; => [1, 2, 3, 'a', 'b', 'c']


// or we can add things to the middle of an array
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes']; 
       // => ["head", "shoulders", "knees", "and", "toes"]

// now we don't have to do parts.splice(1, 0, lyrics);




// for strings, the spread operator is an alternative to String.prototype.split
let string = "Hello";
console.log([...string]); // => [ 'H', 'e', 'l', 'l', 'o' ]

ES6 of the Week - 2 (param defaults & rest/spread)

By beelai88

ES6 of the Week - 2 (param defaults & rest/spread)

Parameter Defaults / Rest and Spread

  • 605