cody cody - 3 months ago 7
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
};
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!

Answer

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: