Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for loop index variables become part of global scope?

Perhaps I'm not aware of how for loop index variables get scoped, but I was very surprised when one of my loops didn't complete, seemingly because a function called from within a loop contained an i for its for loop index as well.

Here's a little script I put together to demonstrate this behavior:

var loopOne = function(test) {
    for(i = 0; i < test.length; i++)
        console.log(getMask(test));
};

var getMask = function(pass) {      
    var s = "";
    for (i = 0; i < pass.length; i++) {
        s = s + "*";
    }
    return s;      
};

loopOne('hello');

If I run this in Chrome and look at the console log, I should see ***** five times. However, I only see it once. Upon further inspection, if I type i in the Chrome javascript console, it will output 6 ( = 'hello'.length + 1). This makes me think that i has become a part of the global scope and is not limited to the scope of the for loop for which it was needed.

Is this correct? If so, what's a better practice for defining the index variable of a for loop in javascript?

like image 810
Ben McCormack Avatar asked May 18 '11 01:05

Ben McCormack


People also ask

Can you get index in for of loop?

You can access the index even without using enumerate() . Using a for loop, iterate through the length of my_list . Loop variable index starts from 0 in this case. In each iteration, get the value of the list at the current index using the statement value = my_list[index] .

What are the scope of for loop variables?

In C/C++, the scope of a variable declared in a for or while loop (or any other bracketed block, for that matter) is from the open bracket to the close bracket.

Can I change the loop index variable within a for loop?

Changing len inside the loop will not help, since range for i variable is determined before the for-loop started and cannot be changed on run time. In other words, once the for-loop started, it forgets what is len , it just remembers that i has to be changed from 1 to 3.

Can JavaScript variables be global?

Description. let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.


1 Answers

In Javascript, variables are scoped with the var keyword. When declaring variables with var, the variable is scoped to the current function. When assigning to a variable without using the var keyword, it is assumed you're talking about an already defined variable in the same or a higher scope. If none is found, the variable is created in the highest scope.

Bottom line: declare all your variables using var.

like image 110
deceze Avatar answered Oct 19 '22 03:10

deceze