const myFunc = (callbackFunc) => {
let value = 50;
callbackFunc(value)
};
myFunc(value => {
console.log(value)
})
I do not understand how and why this block of code runs, my main issue is with the ‘callbackFunc’ parameter which has been sent right back into it’s code block. I saw this on a pre-made video, it logs back the number ’50’ into the console. I really do not understand why?
I have tried re-writing the code as a function declaration as well to see if it will be clearer but i still cannot understand.
2
Answers
Let’s go through this code step by step.
This assigns an arrow function to
myFunc
. It takes one parameter:callbackFunc
(which should be a function formyFunc
to work). Inside the function, a variable namedvalue
is initialized with the value of50
. Then, thecallbackFunc
is called, passing the value of thevalue
variable (i.e.50
) as the first argument.This calls
myFunc
and passes the arrow functionvalue => {console.log(value)}
as the first argument, which would becallbackFunc
inmyFunc
. This function will be called with50
as the first argument insidemyFunc
, sovalue
(the first parameter) will be set to50
. The function only callsconsole.log
with that value, so50
is output to the console.To answer you question, I’mma explain to you the code step-by-step.
The
myFunc
function is declared as a constant arrow function with a parameter calledcallbackFunc
.myFunc
initializes a variable named value with the value 50.The
callbackFunc
parameter calls the value as an argument.The
callbackFunc
parameter in this case is an anonymous arrow function that takes parameters and values and logs them to the console using console.log(value). When you callmyFunc
passing a callback function (value => { console.log(value) }) the following happens:The value parameter of the callback function gets the value of the value variable (50) from the outer range.
The callback function then logs the value 50 to the console.
Which means – on the bottom line – is that the
callbackFunc
is a (kind of) side-effect (or callback) of themyFunc
function.I hope this answer helps !