0

I am confused by the behavior of callback function inside event listener. It works.

function main(){
const value="lorem"
document.addEventListener("click",()=>{
console.log("clicked")
console.log(value)
})
}

main()

But this doesn't works. The error thrown is Uncaught ReferenceError: value is not defined

function handleClick(){
console.log("clicked")
console.log(value)
}
function main(){
const value="lorem"
document.addEventListener("click",handleClick)
}
main()

This also doesn't work.

function handleClick(){
console.log("clicked")
console.log(value)//but this doesn't
}
function main(){
const value="lorem"
document.addEventListener("click",function(){
  console.log(value)//this works 
  handleClick()
})
}
main() 

In the latest case , how can I access value inside the inline callback function but not inside handleClick function called by the inline callback function ? So how can I access value inside callback handleClick? Except doing this:

function handleClick(value){
console.log("clicked")
console.log(value)//now it works
}
function main(){
const value="lorem"
document.addEventListener("click",function(){
  console.log(value)//this works 
  handleClick(value)
})
}
main() 
lorem1213
  • 433
  • 4
  • 11
  • 1
    If `value` is declared inside a function, then its scope is limited to the body of that function. Code outside that function cannot directly access `value`. You could pass `value` as an argument to the other function like you have done in the last code example. – Yousaf Aug 31 '21 at 11:24
  • @Yousaf so even if I add event listener inside a function the callback function cannot access the variables declared inside the function. Is it that? – lorem1213 Aug 31 '21 at 12:03
  • 1
    If the callback function is defined _inside_ function that contains the variable declaration, then the callback can access that variable; otherwise, it can't. – Yousaf Aug 31 '21 at 12:20
  • Oh nice point @Yousaf . Many Many thanks . – lorem1213 Aug 31 '21 at 12:39

0 Answers0