javascriptarraysspread-syntax

Why do I have to use the spread syntax in this case?


I'm attempting to solve this leetcode problem: https://leetcode.com/problems/subsets/

Here's the code that works:

function subset(set) {
    const result = [];

    helper(set, 0, [], result);
    return result;
}

function helper(set, i, slate, result) {
    if(i === set.length) {
        result.push([...slate]);
        return result;
    }

    // exclude i
    helper(set, i+1, slate, result);
    // include i
    slate.push(set[i]);
    helper(set, i+1, slate, result);
    slate.pop();
}

subset([1,2,3])

For this line here:

result.push([...slate]);

Why is it that when I changed it to result.push(slate) or result.push(...slate), neither works even though slate itself is an array?

For the case of result.push(slate): Is this because arrays are stored by reference in JavaScript, so when I do slate.pop(); here, it also pops out that item that is pushed into the result array?

However, I don't understand the other case (result.push(slate)) since it seems that in this case the individual items are pushed in, and not the arrays containing each of those items. Why is that?


Solution

  • You're indeed right about the first case, but for your second case it so because of the signature of Array.prototype.push which is

    arr.push([element1[, ...[, elementN]]])
    

    which is a varargs function (a function that can take an unlimited number of arguments). So when you call

    // given slate = [1,2,3]
    result.push(...slate);
    // is the same as calling
    result.push(1,2,3)
    

    Because your array slate is "spread" into individual arguments to push. Which will add 1,2,3 as individual array elements to result

    While calling

    // given slate = [1,2,3]
    result.push([...slate]);
    // is the same as calling
    result.push([1,2,3])
    

    which is correct in your case and will add an array [1,2,3] as a single element to result.