0

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

foo(1,2,3);

Why above code throws undefined is not a function?

Ele
  • 33,468
  • 7
  • 37
  • 75
john33
  • 61
  • 2
  • 8
  • 2
    This will work `foo(...[a,b,c])` – Get Off My Lawn Nov 10 '18 at 17:20
  • You cannot use an array as an argument in your function construct. – Zlatan Omerović Nov 10 '18 at 17:21
  • I'm wondering the same, it seems JS does something diff when it comes to the function params. This code throws the correct error. ```js function foo(data) { const [b] = data; } a() ``` You code is bringing confusion bc you called your function incorrectly. It should be foo([1,2,3]); – pedroassis Jul 05 '21 at 14:26

2 Answers2

4

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);
charlietfl
  • 170,828
  • 13
  • 121
  • 150
4

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);
Ele
  • 33,468
  • 7
  • 37
  • 75
  • Got a solution but still don't understand it properly `function foo([a, b, c]) { console.log(a, b, c); } foo('1', '2', '3');` – john33 Nov 11 '18 at 15:46