Hi everyone as title says I would like to achieve access to my variable called "Year" outside from my event.
Is that possible?
const ModifyYear = () =>
{
const button = document.querySelector(".button");
let Year = 2022;
button.addEventListener("click", () =>
{
Year = 2023;
})
console.log(Year); //2022
}
CodePudding user response:
Another option is to change your program logic. Here we can use callbacks:
// Your function
const ModifyYear = cb => {
const button = document.querySelector("button");
let Year = 2022;
button.addEventListener("click", () => cb(Year 1));
}
// Call with callback function as parameter
ModifyYear(newYear => console.log(newYear));
<button>Click me</button>
CodePudding user response:
You need to move Year
into the parent scope to access it there:
let Year = 2022;
const ModifyYear = () =>
{
const button = document.querySelector(".button");
button.addEventListener("click", () =>
{
Year = 2023;
})
}