While experimenting with the concept of callbacks, I encountered a scenario where I wanted to confirm that my understanding of the situation was correct.
function greet(callback) { // 'greet' function utilizes a callback
var greeting = "hi"; // 'greeting' variable is defined within the scope
callback() // 'callback' function is called
}
greet(
function() {
console.log(greeting)
});
//Console does not display anything
It's quite interesting. One would expect the callback() to reference its immediate scope and access the 'greeting' variable. However, when I move the definition of the 'greeting' variable to the global execution context, then it works as expected.
var greeting = 'hi' // 'greeting' variable is defined globally
function greet(callback) { // 'greet' function takes a callback
callback() // 'callback' function is invoked
}
greet(
function() {
console.log(greeting)
});
//Console logs: 'hi'
Could this be because the callback() function that logs the variable is actually declared in the global context? Therefore, rather than searching inside greet(), it directly looks in the global environment due to its declaration.
I just wanted to ensure that I correctly comprehend what's happening here, instead of facing some unexpected scope or block-related issue.