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!
Create a new scope
for (var i = 0; i < 3; i++) {
(function(i) {
document.getElementById(i).onclick = function() {
console.log(i);
}
}(i));
}
In Javascript, scope is not created by brackets (contrary to the C-like syntax). Scope is however, created in functions, so one way is to extract the call into a function (updated):
<script>
for (var i = 0; i < 3; i++) {
logCall(i);
}
function logCall(i) {
document.getElementById(i).onclick = function() {
console.log(i);
}
}
</script>
This has the added benefit of making the code a bit more reusable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With