0
var mult = (function(){
 var cache = {};
 var calculate = function(){
 var a = 1;
 for(var i = 0, l = arguments.length; i < l; i++){
 a = a * arguments[i];
 }
 return a;
 }
 return function(){
 return calculate(arguments);
 }
})();
console.log(mult(1, 2));

Above is my code, I expect the mult function will give me value 2, but instead it outputs NaN. I changed the line calculate(arguments) to caculate.apply(null, arguments) and it worked. I don't know why the old code doesn't work? Why do I need to use apply in this case? What does null represent here?

asked Jan 4, 2018 at 22:19
3
  • Why are you going for this much indirection anyway? Commented Jan 4, 2018 at 22:21
  • Why this code is so much complicated? Commented Jan 4, 2018 at 22:21
  • 2
    try return calculate(...arguments); Commented Jan 4, 2018 at 22:24

1 Answer 1

3

Your calculate function wants separate arguments, but you passed in an array 1. Using .apply spreads the content of the array for you.

1 Technically an array-like arguments object that does not inherit from Array.

answered Jan 4, 2018 at 22:21
Sign up to request clarification or add additional context in comments.

6 Comments

Well, technically he passed in the array-like arguments object, but close enough. ;)
You are absolutely correct, but using the word "array" is easier to understand than "array-like arguments object" :)
Marginally easier to understand, but less accurate.
I know, I just wanted to be pedantic to pre-empt follow up questions about why certain array functions weren't working.
but why did it use apply.(null..)? what does null represent?
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.