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>