If I have a variable in an outer function, and an internal function that changes that variable, why does that variable revert back to its original value?
// Check which type of event registration browser supports
function addEvent(eventTarget, eventType, eventHandler){
if (window.addEventListener){
eventTarget.addEventListener(eventType, eventHandler);
}
else if (window.attachEvent){
var eventType = "on" + eventType;
eventTarget.attachEvent(eventType, eventHandler);
}
}
// Check if browser supports DOMContentLoaded
var DOMContentLoadedSupported = "no";
addEvent(document, "DOMContentLoaded", function(){
DOMContentLoadedSupported = "yes";
})
alert(DOMContentLoadedSupported) // alerts "no" not "yes". Why??
The function will modify the variable, but that will happen AFTER your alert, so you see “No” in the alert cause the alert happens before the variable gets modified.