Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: localise variables in block [duplicate]

Tags:

javascript

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!

like image 457
Michael Avatar asked Jul 06 '13 14:07

Michael


2 Answers

Create a new scope

for (var i = 0; i < 3; i++) {
  (function(i) {
    document.getElementById(i).onclick = function() {
      console.log(i);
    }
  }(i));
}
like image 60
Prinzhorn Avatar answered Oct 31 '22 15:10

Prinzhorn


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.

like image 31
Igor Avatar answered Oct 31 '22 14:10

Igor