Home > Software design >  JavaScript array destructuring issue when used as function parameters
JavaScript array destructuring issue when used as function parameters

Time:08-30

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related