Search code examples
javascripthoisting

Using variable before initialization. JS


Recently I found this piece of code and this is a "find what is wrong and modify" type of exercise. The purpose is to make this code work without moving the message variable on top of the code and I am pretty curious how I can achieve that.

function myMethod(cb) {
    cb();
}

myMethod( () => console.log(message) );

const message = "My message";

Solution

  • First thing came to my mind was to declare variable with var keyword, then program won't throw error but still doesn't print the message. you could never carry the initilization to the top of the file without using event loop.

    Appareantly only way would be surrounding myMethod( () => console.log(message) ) inside a setTimeout function

    setTimeout(() => {
      myMethod( () => console.log(message) )
    }, 0)
    

    This way the execution of function will be delayed until call stack is empty. Then it'll execute the function with the current value which will be set by then.