Reputation: 1645
I'm a little bit confused on the following code below. The part that I don't understand is how does the result parameter equal to the result of the callback(x+y)
. Can someone explain this and perhaps the order of steps that this executes in?
function add(x,y, callback){
callback(x+y)
}
add(3,4, function(result){
console.log(result) //logs out 7
})
I know that 3+4 is 7, but I don't specifically understand how the result parameter gets this 7 value.
Upvotes: 2
Views: 49
Reputation: 6740
Great question, and once you understand this, it's going to open a lot of doors in Javascript.
Let's look at what happens without a callback:
function add(x, y) {
return x + y;
}
add(1, 2) // returns 3
When you return x + y
, that's what you get back from the function.
Now let's introduce a new function, but not as a callback.
function add(x, y) {
return x + y;
}
function logResult(result) {
console.log(result)
}
var result = add(1, 2) // 3
logResult(result) // outputs "3"
As you see, we call add
, get the result, and then pass it into logResult
, which outputs it to the console.
If we pass logResult
as a function in the third argument of add
, and then we call it inside add
with the result
, it's effectively the same thing!
function add(x, y, callback) {
var result = x + y;
// we're calling the function that gets passed in
// which is `logResult`
callback(result)
}
function logResult(result) {
console.log(result)
}
add(x, y, logResult) // outputs "3"
And now we circle back to your example, which reduces everything to the minimal code needed:
function add(x, y, cb) {
cb(x + y);
}
add(1, 2, function (result) {
console.log(result)
}); // outputs "3"
In JS you can pass functions into other functions. The function that receives another function as an argument can call it. That's what you have here. You can also reduce this even further:
function add(x, y, cb) {
cb(x + y)
}
add(1, 2, console.log) // outputs "3"
add(1, 2, console.error) // outputs "3" in error format
Upvotes: 1
Reputation: 114024
This code:
function add(x,y, callback){
callback(x+y)
}
add(3,4, function(result){
console.log(result) //logs out 7
})
is exactly the same as this:
function add(x,y, callback){
callback(x+y);
}
function output(result){
console.log(result);
}
add(3,4, output);
So the function add takes 3 parameters, when calling add(3,4,output)
,
x
is assigned the value 3
y
is assigned the value 4
callback
is assigned a pointer to the function output
Since callback
in the call above is a pointer to the function output
, when you do callback(x+y)
you're actually calling output(3+4)
.
It's nothing special. It's just a result of javascript treating functions as first class values.
Upvotes: 0
Reputation: 288680
The add
function is called with these arguments:
x = 3
y = 4
callback = function(result) { console.log(result) }
That function sums x+y
. That produces 7
.
Then it calls the callback
function with this argument:
result = 7
That function logs 7
in the console
Upvotes: 0