0

I am trying to work with higher order functions, in an attempt to be a better javascript developer.

The error I'm getting from the code below is TypeError: myArray.reduce is not a function I swear I'm following the correct design pattern.

function myFunction(myArray) {
    return myArray.reduce((prev, curr) => prev * curr);
}
var myArray = [3, 2, 3]
var myObject = myFunction.apply(myObject, myArray); // Will each element in array be multiplied?
Chris Clark
  • 283
  • 1
  • 12

2 Answers2

4

You want to use .call instead of .apply.

.call will pass in each object and pass them directly to the function, while .apply will take an array of parameters and pass them in as each separate variable.

You can see the effects below, with this simple script:

function myFunction() {
    console.log(arguments);
}
var myArray = [3, 2, 3];

myFunction.call(null, myArray);
/*
 Will echo out {
   "0": [
    3,
    2,
    3
 ]}
 
 The first variable will contain the entire array
*/

myFunction.apply(null, myArray);
/*
 Will echo out {
  "0": 3,
  "1": 2,
  "2": 3
 }
 
 The first variable will be 3, the second 2, and the third 3
*/
Goodbye StackExchange
  • 21,680
  • 7
  • 47
  • 83
1

Instead of using

var myObject = myFunction.apply(myObject, myArray);

Use

var myObject = myFunction.call(myObject, myArray);

Since function.prototype.apply method takes each items of array as a parameter. myArray parameter becomes 3, 2, 3 so It behaves like your function took 3 parameters.