Reputation: 199
I have some events logged in an if/else statement, for example:
function foo(shown) {
if (shown == "div1") {
function check() {
var var_2 = new Date().toISOString();
console.log("time", window.var_1 + " - " + var_2);
}
var button = document.getElementById("button2");
button.addEventListener("click", check);
} else if (shown == "div2") {
var var_3 = new Date().toISOString();
console.log("time:", var_2 + " - " + var_3);
}
var button = document.getElementById("button");
button.addEventListener("click", check);
return true;
}
The problem is that here:
} else if (shown == 'div2') {
var var_3 = new Date().toISOString();
console.log('time:', var_2 + ' - ' + var_3 );
}
var_2
is not reachable, I am getting Uncaught ReferenceError: var_2 is not defined
, how can I access to this variable and log it into the console?
Upvotes: 0
Views: 61
Reputation: 1497
Declare your variables at the beginning of your function:
function foo(shown) {
let var_2 = "";
let var_3 = "";
if (shown == "div1") {
function check() {
var_2 = new Date().toISOString();
console.log("time", window.var_1 + " - " + var_2);
}
var button = document.getElementById("button2");
button.addEventListener("click", check);
} else if (shown == "div2") {
var_3 = new Date().toISOString();
console.log("time:", var_2 + " - " + var_3);
}
var button = document.getElementById("button");
button.addEventListener("click", check);
return true;
}
Upvotes: 1