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?
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] .
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With