cody
cody

Reputation: 681

Why this function invocation return a string and not a number

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!

Upvotes: 0

Views: 36

Answers (2)

zerkms
zerkms

Reputation: 255015

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:

Upvotes: 1

sma
sma

Reputation: 9597

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.

Upvotes: 3

Related Questions