skip to Main Content
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


  1. Let’s go through this code step by step.

    const myFunc = (callbackFunc) => { 
        let value = 50;
        callbackFunc(value);
    };
    

    This assigns an arrow function to myFunc. It takes one parameter: callbackFunc (which should be a function for myFunc to work). Inside the function, a variable named value is initialized with the value of 50. Then, the callbackFunc is called, passing the value of the value variable (i.e. 50) as the first argument.

    myFunc(value => { 
        console.log(value);
    });
    

    This calls myFunc and passes the arrow function value => {console.log(value)} as the first argument, which would be callbackFunc in myFunc. This function will be called with 50 as the first argument inside myFunc, so value (the first parameter) will be set to 50. The function only calls console.log with that value, so 50 is output to the console.

    Login or Signup to reply.
  2. 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 called callbackFunc.
    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 call myFunc 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 the myFunc function.

    I hope this answer helps !

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search