Rest parameter anywhere

# Егор Николаев (11 years ago)

Long story short:

function test( a = 1, b = 2, ...rest, c = 4, d = 5) {
console.log(a, b,rest, c, d)
}

test();                // 1, 2, [], 4, 5
test(9, 8);            // 9, 8, [], 4, 5
test(9, 8, 7, 6);      // 9, 8, [], 7, 6
test(9, 8, 7, 6, 5, 4);// 9, 8, [7, 6], 5, 4

let [a = 1, b = 2, ...rest, c = 4, d = 5] = [];                // a == 1, b == 2, rest == [], c == 4, d == 5
let [a = 1, b = 2, ...rest, c = 4, d = 5] = [9, 8];            // a == 9, b == 8, rest == [], c == 4, d == 5
let [a = 1, b = 2, ...rest, c = 4, d = 5] = [9, 8, 7, 6];      // a == 9, b == 8, rest == [], c == 7, d == 6
let [a = 1, b = 2, ...rest, c = 4, d = 5] = [9, 8, 7, 6, 5, 4];// a == 9, b == 8, rest == [7, 6], c == 5, d == 4

This is easy-to-implement but very important destructuring pattern. If it can't be in ES6 maybe in ES7?

Issue: ecmascript#2034 Previous discussion: esdiscuss/2012-June/023393

CoffeeScript and Python 3 has this feature as well.

Examples:

let [firstOne, ...rest, lastOne] = document.findAll(".someClass");
firstOne.classList.add("first");
lastOne.classList.add("last");


function download (...files, callback) {
    for (let file of files) {
      <...>
      if (downloaded) callback();
    }
}

download( 'file1.txt', 'file2.txt', function() {
    alert('ready');
});
# Tab Atkins Jr. (11 years ago)

You skipped the most interesting case - what to do when the list is almost long enough to accommodate all of the non-rest params.

let [a = 1, b = 2, ...rest, c = 4, d = 5] = [9, 8, 7];

It seems, from your second test case, that a=9 and b=8, but which variables gets a value of 7 - c or d?

# C. Scott Ananian (11 years ago)

FWIW, in coffeescript c gets the 7:

f = (a=1,b=2,c...,d=3,e=4) -> alert "a=#{a} b=#{b} c=#{c} d=#{d} e=#{e}"

f(8,9,10)  // alerts "a=8, b=9, c= d=10 e=4"
# Егор Николаев (11 years ago)
let [a = 1, b = 2, ...rest, c = 4, d = 5] = [9, 8, 7];

a == 9, b == 8, rest == [], c == 7, d == 5 obviously. As in coffeescript

# Boris Zbarsky (11 years ago)

On 4/16/14 8:27 AM, Егор Николаев wrote:

let [a = 1, b = 2, ...rest, c = 4, d = 5] = [9, 8, 7];

a == 9, b == 8, rest == [], c == 7, d == 5 obviously. As in coffeescript

I assume multiple rest parameters are a syntax error?

# Егор Николаев (11 years ago)

I assume multiple rest parameters are a syntax error?

No doubt

# Andrea Giammarchi (11 years ago)

wasn't that obvious to me ... anyway, the first, ...mess, last example convinced me ^_^