Javascript for loop - Iterate Odd Numbers With a For Loop

Hello Campers

Am doing the exercise on ‘the for loop’ i got the code running but i am wondering what is the use of var in the loop. Please help.

// Example
var ourArray = [];

for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}

HERE IS WHAT I HAVE

// Setup
var myArray = [];

// Only change code below this line.
for(i = 1; i < 10; i += 2)
{
myArray.push(i);
}

If you don’t include the var keyword, it will create the variable i globally, which could be a huge problem if you have multiple for loops, each using the same variable for counting. You want to include that keyword so the variable gets properly dealt with when the garbage collector cleans up unused code.

1 Like

http://devdocs.io/javascript/statements/var

And var i will be global if the execution context is global. Inside a function it would be local.

It’s actually better to use let instead of var for things like for loop indices, but older browsers don’t support it so I’d probably still avoid let except in a server side environment where you know the version of the interpreter. http://caniuse.com/#search=let

Also, in real code you want to keep things from running in the global scope so you don’t end up with a bunch of i’s, j’s, x’s, n’s all over the place from this. That is why you see this used: https://en.wikipedia.org/wiki/Immediately-invoked_function_expression

2 Likes

var i = 1; // set the initial value for variable i
i < 10; // if variable i is less than 10, do something ( in your case, push variable i to myArray)
// number 1 is now in myArray
i += 2; // add 2 to variable i ( i becomes 3 )
and repeat…
i < 10; // yes, it’s 3. So push it to myArray
// myArray looks like [1, 3]
i += 2; // add 2 to variable i ( i becomes 5 )
and repeat…
i < 10; // yes, now it’s 5. Push 5 to myArray
// myArray looks like: [1, 3, 5]
i += 2; // add 2 to variable i ( i becomes 7 )
and repeat…

1 Like