cody cody - 11 months ago 45
Javascript Question

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

Why does this code return a string
? 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!

Answer Source

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']));