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?
5
  • 2
    Why not simply var myObject = myFunction(myArray); ? Commented Aug 11, 2016 at 17:25
  • What browser/version are you using? I know we saw that chrome 44 didn't support => but 47 or 48 did. Commented Aug 11, 2016 at 17:25
  • @Arnauld I am attempting to work with apply, arrow functions, and reduce patterns. Commented Aug 11, 2016 at 17:26
  • @klog I am using v52. Commented Aug 11, 2016 at 17:26
  • @ChrisClark Fair enough. Then you should use myFunction.apply(myObject, [myArray]) Commented Aug 11, 2016 at 17:28

2 Answers 2

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
*/

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

2 Comments

Alternatively, myFunction.apply(myObject, [myArray]).
@ChrisClark more reading -> stackoverflow.com/questions/1986896/…
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.

Comments

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.