J. Doe J. Doe - 7 months ago 13
Javascript Question

javascript callback clarification

I know there is a lot of info out there on callbacks, but I am still struggling a little to grasp it. I wrote the following code just trying to see if I could understand the flow of callbacks and feel like I am close, but am still missing something:

var sum = function(a, b){
return a + b;
};

var times = function(x, y){
return x * y;
};

var math = function(sum, times, callback){
console.log(sum + times);
callback(times);
};

math((1,2),(3,3), function(totalizer){
console.log(totalizer);
});


this logs 5 and 3 to the console(which seems to be the last two values(2 +3) and the last value in the times(3), when I'd like it to return 12 9. If you see the issue please let me know, I appreciate the help. Also, any info you have to help clarify what I'm doing wrong would be great.

thanks

Answer

You are not calling the sum or times function even once. The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand. (MDC) (https://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/)

What you tried to do is probably this:

math(sum(1,2),times(3,3), function(totalizer){
  console.log(totalizer);
});

This will log 12 and 9 as you had expected.

Edit to answer your comment:

You are mixing up variable names and function names:

var math = function(sum, times, callback){
  console.log(sum + times);
  callback(times);
};

is exactly the same as

var math = function(foo, bar, callback){
  console.log(foo + bar);
  callback(bar);
};

If you try to search for javascript variable scopeor something similar, you'll probably find a lot of posts that clarify your question.