2

I'm new to JavaScript, so I'm sorry if this question is too stupid. I was told that when you create a for-loop, you should write:

for (var i = 0; i < 10; i++)

but sometimes I forget to put var before the i:

for (i = 0; i < 10; i++)

and it works the same. Do I need to create the variable i?

What's the main difference between

var i = 0

and

i = 0

in a for-loop?

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
user3347814
  • 1,138
  • 9
  • 28
  • 50

7 Answers7

5

Not creating the variable using var still creates the variable. The difference is that it belongs to the global namespace. This should be avoided because it increases the chance of a collision with variables having the same name from other functions.

isherwood
  • 58,414
  • 16
  • 114
  • 157
2

When you declare the variable with var then it's scope would be limited,

When you don't use var then the variable would be in global scope. Which means you can access this variable from anywhere.

Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
1

Variables declared without var are global variables accessible from anywhere. Using global variables is considered as an anti-pattern and should be avoided.

Regarding your loop it is not necessary but bad practice

Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
0

you can define varible before cycle,like so

var i = 0;
for(i;i<10;i++)

and that will work.So you can define varible just before you for cycle.var in cycle is the same, as it was just before it.

fhntv24
  • 384
  • 3
  • 11
0

You can use the for loop as like as the while loop.

var i=0;
for(;;)
{
   // something need to perform
   i++;

   // breaks your loop here
   if(i > 10)
      break;
}
Soundar
  • 2,569
  • 1
  • 16
  • 24
0

The difference is that your browser needs to know whether you want to declare a variable 'i' with value '0' OR you want to assign '0' to the already existing variable 'i'.
The browser (or most of them) will know whether there is already a variable with such name because it can simply look up its library of variables. But for us humans, it is very useful to put 'var' in front of it so we know that this is the declaration.

In other languages, 'var' or any datatype definition like 'int','char' or 'bool' is necessary, but at least in Javascript, it is simply written in terms of order and ease of reading code.

function someCode('awesome', 'hyper-fast'){
...
...
i = 0; // if this is a declaration, write 'var', so we know !
...
...
return 'backHome';
}
Sam
  • 251
  • 1
  • 19
0

Basically, your code works because you are creating a global variable. It is best practice to explicitly create a variable using var inside of your loop. This is what I call a garbage variable. It never leaves the scope of the loop so you can continue to use the same variable name for all of your loops(unless you are nesting).