I have some js code, which is doing what I want, but I can’t figure out why. Can someone please point me to some resource that explains the JS rules for when variable values are determined? Also, can anyone tell me a simple way to peek under the hood and see the process for myself?
Here is the code:
<!DOCTYPE html>
<html>
<body>
<div id="demo">OUTPUT GOES HERE</div>
<div id="demsTest1">Test 1</div>
<div id="demsTest2">Test 2</div>
<div id="demsTest3">Test 3</div>
<div id="demsTest4">Test 4</div>
<script>
var testVar = 2;
function addLstn(i) {
document.getElementById("demsTest" + i).addEventListener("click", function(){
document.getElementById("demo").innerHTML += "<br>i = " + i;
/*i has the value it held when the event listener was added,
apparently because this value is substituted, and
the variable no longer exists*/
/*the direct substitution in the previous line,
is the bit I want to peek at -
where would I find the newly substituted line
" ... += "<br>i = " + 1/2/3/4 etc??*/
testVar = testVar*i; //testVar updates, apparently because it is declared outside the function
document.getElementById("demo").innerHTML += "; testVar = " + testVar;
});
}
for (i=1; i<5;i++) {addLstn(i);}
</script>
</body>
</html>
I tried this, and got what I expected, but I can’t explain it