-3

According to the JavaScript documentation, variables created within a function are local to that function. However, I found that not using the literal var when the variable is declared inside a for-loop causes unexpected behaviour (e.g. https://jsfiddle.net/carlesaraguz/ao77ac2L/)

Why is that?

function iterate1() {
    var array = ["hello", "world"];
    var str = "";
    for (i = 0; i < array.length; i++) {
        str += "iterate0 --- " + i + ": " + array[i] + "<br>";
        iterate2(array);
        str += "iterate0 --- " + i + ": " + array[i] + "<br>";
    }
    document.getElementById("output0").innerHTML = str;
}

function iterate2(arr) {
    var str = ""
    for (i = 0; i < arr.length; i++) {
        str += "iterate1 --- " + i + ": " + arr[i] + "<br>";
    }
    document.getElementById("output1").innerHTML = str;
}

$(function() {
    iterate1();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="output0"></p>
<p id="output1"></p>
Lewis
  • 14,132
  • 12
  • 66
  • 87
Carles Araguz
  • 1,157
  • 1
  • 17
  • 37

2 Answers2

1

Here's an example of what happens when you forget to put var. The scope of your variable becomes global

(function() {
    myVar = 1;
    console.log("myVar should be 1: " + myVar); // should be 1
    setTimeout(function() {
        console.log("myVar should be 1, but isn't: " + myVar); // should be 1, but isn't 
    }, 100);
})();

(function() {
    for(myVar = 1; myVar < 10; myVar++) {
        // nothing, just increment var
    }
})();

You'll notice that there are two functions isolated from each other, but are actually using the same myVar

To add, var's scope is the function it's enclosed in after it's declaration, regardless if it's declared in a for loop or if or any other type of block level statement.

In your particular case, here's what's happening.

iterate0 - 0 - hello | declared i as global with value of 0, print
iterate1 - 0 - hello | change value of i to 0, print and then increment i after
iterate1 - 1- world | i is 1 from previous incrementation, print, increment again after the loop
iterate0 - 2 - undefined | i is 2 from previous incrementation, print, increment again bumping it up to 3
end

andyw_
  • 490
  • 5
  • 15
1

By not using "var" before declaring a variable, you are creating a global variable instead of a local one.

function f1() {
  for (var i = 0; i...) {
    // i is local to this function 
  }
}

function f2() {
  for (i = 0; i...) {
    // i is a global variable
  }
}

See https://stackoverflow.com/a/1470494/5780021 for more info about this

Community
  • 1
  • 1
Alex R
  • 624
  • 3
  • 10
  • This is a general information; it did not answer the context of the question by explaining what exactly happen in this case to get such output. So it’s not a complete answer for the question. – HDJEMAI Jan 12 '16 at 17:00