I try to understand variable scope in Javascript. Here is what I am doing:
<script>
for (var i = 0; i < 3; i++) {
document.getElementById(i).onclick = function() {
console.log(i);
}
}
</script>
The output is always 3, and I understand that's because i
has been retained by reference. How do I localise i
so it can log incremented value?
Thanks!
update
Thanks guys for quick and decent responses. the solutions are indeed of help!
Initially, I was trying a similar approach to @GrailsGuy, here it is:
<script>
for (var i = 1; i <= 3; i++) {
document.getElementById(i).onclick = function() {
console.log(logCall(i));
}
}
function logCall(i) {
return i;
}
</script>
But it looks like i
isn't being localised. Cannot figure out why!