john33
john33

Reputation: 61

Getting undefined is not a function while array destructing

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

foo(1,2,3);

Why above code throws undefined is not a function?

Upvotes: 0

Views: 395

Answers (2)

charlietfl
charlietfl

Reputation: 171690

You could spread the arguments and assign the variables inside the function

const foo = (...args) => {
  const [a,b,c] = args
  console.log(a,b,c);
}

foo(1,2,3);

Upvotes: 4

Ele
Ele

Reputation: 33726

Because the js engine didn't match any iterable object from the parameters.

Look at this example

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

// This time, we are passing an array which is iterable
foo([1, 2, 3]);

An alternative is using the Spread syntax and then the function apply to pass the whole set of params as separated params to the function console.log.

function foo(...params) {
  console.log.apply(undefined, params);
}

foo(1, 2, 3);

Upvotes: 4

Related Questions