0

I want to store a function and its arguments in an object and invoke it via this object, as follows:

var fn = function(x, y) {
  return x + y
};
var obj = {
  'args': [2, 3],
  'func': fn
};
console.log(obj.func(obj['args']));

Why does this code return a string "2,3undefined"? It's not even '23' if it receives the arguments as strings and + concats them. How do I make it return 5 as expected? Thanks a bunch!

1
  • 2
    Because the first argument you pass is the array [2,3], the second is undefined since you don't pass anything to it. The + operator is overloaded, it does addition, concatenation or type conversion to Number depending on the context. Commented Sep 6, 2016 at 1:02

2 Answers 2

3

Try using apply to call the function instead:

var fn = function(x,y) {return x + y };
var obj = { 'args': [2, 3], 'func' : fn};
console.log(obj.func.apply(obj, obj['args']));

In your example, what you're actually doing is passing the entire array as the 'x' argument and an undefined y value. Apply will call the function with the supplied array as the arguments.

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

1 Comment

The OP can also use ECMAScript 2015 spread syntax in the call: obj.func(...obj['args']). ;-)
1

You are passing an array as a single parameter to the function

var fn = function(x,y) {return x + y };

And your call looks like fn([2, 3])

So in runtime the x equals to the array, and y equals to undefined. You passed nothing.

[2, 3] + undefined

is evaluated into a string, since the scalar value of [2, 3] is 2,3. And string + undefined expression casts the second operand to string as well, hence 2,3undefined.

To "fix" it - use the Function.prototype.apply:

fn.apply(null, [2, 3])

or in your case

console.log(obj.func.apply(null, obj['args']));

References:

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.