0

I was writing the function bellow and it came to my mind to ask if there is another way to instantiate the counter variable in the loop other than using the var key word? Also if it possible in another context not in a for loop.

Obviously this code doesn't work.

function everyOther(arr) {
    var sum =0;
    for(i=0;i<arr.length;i+=2){
        sum+=arr[i];
    }
    return sum;
}

This one works. Can I omit the var keyword somehow?

function everyOther(arr) {
    var sum =0;
    for(var i=0;i<arr.length;i+=2){
        sum+=arr[i];
    }
    return sum;
}
Henry Lynx
  • 1,099
  • 1
  • 19
  • 41
  • 3
    Probably specifying what "did not work" would help you come to the answer yourself. – icedwater Jun 21 '13 at 06:10
  • This is because that is the first time you are defining the variable `i`. – Abhranil Das Jun 21 '13 at 06:10
  • 1
    So what's happening here? What's your output ? – Software Engineer Jun 21 '13 at 06:11
  • 3
    Unless `i` is global and something changed it outside the for loop, I don't see why the first loop shouldn't work... what "did not work"? – Jcl Jun 21 '13 at 06:11
  • I am following a course at Learn Street and the positive results are predefined (I guess) meaning I need to write exactly what the teacher has put as answer. It did not let me pass till I defined the var i in the for loop. If I have defined it out-side the loop it would have worked well? – Henry Lynx Jun 21 '13 at 06:13
  • what "did not work"? what's happening here? What's your output? Can you explain more about this? – Amol M Kulkarni Jun 21 '13 at 06:17

3 Answers3

3

It does work as a standalone. Only it sets the global i variable, instead of using a local one - see What is the purpose of the var keyword and when to use it (or omit it)?.

Yet, when you call everyOther from another snippet that also uses the global i variable, they might interfere. Especially if from another loop, it might disturb the outer condition and lead to an infinite loop.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

You need to at least declare a variable before you can use it. You could've also done:

function everyOther(arr) {
var sum =0;
var i = 0;
for(i=0;i<arr.length;i+=2){
    sum+=arr[i];
}
return sum;
}
LukeP
  • 1,505
  • 1
  • 16
  • 25
  • 1
    You *should* declare a variable before use, but it's not required to do so in Javascript. You just end up with a global variable instead of a local one without the "var" statement. – Mark Bessey Jun 21 '13 at 06:28
0

Because you have to declare any variable before using it and if you don't use that means you have already declared it as a global variable.

Using var is always a good idea to prevent variables from cluttering the global scope and variables from conflicting with each other, causing unwanted overwriting.

Using var means you are specifying it as Local variable.
Not specifying var means you are making it as Global variable.

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105