I'm pretty new to JS and the whole idea of closures. Here's a trivial example of some code that makes use of closures.
window.onclick = function() {
const x = "WOOHOO!";
(function myFunc() {
console.log(x);
})();
}
Here, the inner IIFE has access to the x variable because of closures. However, I'm not entirely sure why the following does not work the same way, and requires the passing of a variable.
window.onclick = function() {
const x = "WOOHOO!";
myFunc();
}
function myFunc() {
console.log(x);
}
This does not work. You have to do
window.onclick = function() {
const x = "WOOHOO!";
myFunc(x);
}
function myFunc(val) {
console.log(val);
}
Can someone provide a simple but somewhat detailed explanation of why the second example does not work and requires the passing of an argument?