0

When I destructure an empty array and pass it as a parameter to my function, it appears in places that I'm not expecting.

This is how you're supposed to destructure an array into function parameters:

let test = (one, two, three) => {
  console.log(one);
  console.log(two);
  console.log(three);
};

test(...[1, 2, 3]);
// returns 1, 2, 3

However in my case, I want to destructure an array as a single function parameter.

Sometimes this array is empty, but it otherwise only has one object. It's not working as expected:

let test = (one, two, three) => {
  if (three === undefined) {
    console.log("3 is undefined");
  }
};

test(...[], 2, 3);
// 3 is undefined

three is undefined, but this is certainly not true, because one is undefined.

What is going on?

1
  • "because one is undefined" - What do you mean by this? In your last example one is not undefined, it is 2. Commented Aug 30, 2022 at 0:07

2 Answers 2

3

When you spread an iterable into an argument list, all elements of the iterable will be inserted into the argument list at that point, and the rest of the arguments will start at the end of that. But an empty array contains no elements. Putting this:

...[],

inside an argument list does nothing at all - it's equivalent to that one segment not being there at all, because it inserts no arguments, and the arguments to the right of the ...[], start at the same point they would otherwise.

test(...[], 2, 3);

is the same as

test(2, 3);

So

let test = (one, two, three) => {

one and two get numbers assigned to them, and three is undefined - because two arguments were passed total.

Also note that there is no destructuring at all in your question - all you're doing is invoking spread syntax.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the most intuitive explanation. I guess the source of my confusion was that ...[] essentially amounts to nothing, rather than a type like undefined. You're right about spread syntax, but I think it's also referred to as destructuring in the case of "unpacking values from an array"
0
let test = (one, two, three) => {
  if (one === undefined) {
    console.log("3 is undefined");
  }else{
  console.log(one)
  }
};

test(...[], 2, 3);

first parameter is 2 and second is 3

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.