Getting variable value out of for loop [duplicate] - javascript

This question already has answers here:
Why variable hoisting after return works on some browsers, and some not?
(5 answers)
Closed 5 years ago.
I am currently using a for loop in javascript to iterate over an array.
Its working fine, but I can still get the variable value used in for loop outside the loop. I am not able to find the cause.
Here is the code snippet.
var list = ['delhi','mumbai','pune','kolkata'];
for (let i = 0, max = list.length ; i < max ; i++ ){
var current_city = list[i];
//other code goes here
}
console.log(current_city);
It's printing 'kolkata' outside the for loop.

You just need to set var current_city to let current_city . . .
var list = ['delhi','mumbai','pune','kolkata'];
for (let i = 0, max = list.length ; i < max ; i++ ){
let current_city = list[i];
//other code goes here
}
console.log(current_city); // shows error, as you expect.

That behavior is correct. You keep reassigning the value of current_city so it just logs the last one. If you want them all logged, just move the console.log inside the loop.
var list = ['delhi','mumbai','pune','kolkata'];
for (let i = 0, max = list.length ; i < max ; i++ ){
var current_city = list[i];
console.log(current_city);
}

JavaScript doesn't have block scope, just function scope. Since the initialization of current_city is within one function, that variable is accessible anywhere else in that same function. These variables are not local to the loop, i.e. they are in the same scope the for loop is in.
You keep reassigning the value of current_city so it is assigned the last item from the array when the loop ends. Hence you get the result kolkata

Related

JS Can't use array initialized within for loop

I'm having trouble understanding how scoping works in JS, my background is in R and Python.
This is a toy example. The games_array always prints out as empty at the end. And the array variable doesn't seem to be present in the console.
for(var row_i = 0; row_i < 50; row_i++){
var games_array = [];
if(row_i % 2 == 0){
console.log(data[row_i].name);
games_array.push(data[row_i].name);
}
}
console.log(games_array);
But then this works:
var games_array = [];
for(var row_i = 0; row_i < 50; row_i++){
if(row_i % 2 == 0){
console.log(data[row_i].name);
games_array.push(data[row_i].name);
}
}
console.log(games_array);
I don't understand why I can't create an empty array and use it within a for loop.
I need to wrap this inside an outer loop and use the games_array in the outerloop.
Any help is appreciated.
The problem is not with scoping. After all, since you declared the variable using var instead of let, the scope extends outside of the for loop. The problem is that each time the loop runs, it sets games_array to [], which means the array gets cleared each time the loop runs.
In the second example, you only initialize the array once, which is why it works.

JavaScript Why does the index of a for loop add one when adding eventlisteners [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 4 years ago.
I have a question which might sound silly. In the code below there are 2 console.log(i) statements. I want to know why does the second console.log(i) statement returns value of 2 and not 1 as the former on the first iteration (i.e. 1st statement i=n, 2nd: i=n+1). Shouldn't both be equal to 1 until the end of the loop?
function toggleWrapper(){
var el1 = document.querySelectorAll('[class="tCell entryDesc"]');
for (var i = 1; i < el1.length; i++) {
console.log(i);
el1[i].addEventListener('click', function(ev){
console.log(i);
var el2=document.querySelectorAll('[class="additionalInfoContainer"]');
if (el2[i-2].clientHeight) {
el2[i-2].style.maxHeight = 0;
}
else{
el2[i-2].style.maxHeight = el2[i-2].scrollHeight +"px";
}
},
false);
}
}
The problem is that the variable i, within each of your addEventListener() functions, is bound to the same variable outside of the function. simply change your for loop to :
for (let i = 1; i < el1.length; i++)
In the loop with let based index, each iteration through the loop will have a new value of i where each value is scoped inside the loop, so your code would work fine.
i think is something in your code because if you try to make a for loop with two "console.log()" it doesn't do that

Is it Possiable to call to previous increments of a variable?

for example lets say i have a loop that is doing basic counting, while the variable is less than 16 the loop will run and at the end of the loop you add 2 to the variable and add one to a "count" variable
what i want to know is if its possible to callback to any of the previous variables for either variable for example can i count all the times count % 2 === 0?
im not quite sure if once a variable makes any kind of change if all previous versions of that variable are gone
http://codepen.io/anon/pen/Gojoxm
var two = 0;
var count = 0;
while ( two < 16) {
two += 2;
count++;
};
console.log(count);
If I understand you right, then no, you cannot. When you assign a new value to a variable, the previous value is lost.
You have to either run this loop again or store intermediate values in an array:
var values = [];
var two = 0;
while (two < 16) {
two += 2;
values.push(two);
}
console.log(values.length); // the same result
Then, you will always be able to do whatever you want with these values.
For example, you can check if there were any odd values:
var anyOddNumbers = values.some(function(x) { return x % 2 === 1; }); // false

simple javascript variable issue in js+iim code

var variable=1;
var sample="CODE:";
sample += "URL GOTO="+variable;
for(i=0 ; i<10 ; i++){
iimPlay(sample);
variable++;
}
I'm making a bot using javascript+imacros (the code below is just a sample to understand the issue), and I need the variable to be increased by 1 for every loop. Any help?
The problem was that the variable value was not incremented inside your loop and all your loop see is the global level scope variable which contains a value of one.
Here is a jsfiddle to demonstrated the output: https://jsfiddle.net/larryjoelane/sv2bc7Lm/
//initialize variable
var variable = 1;
//changed i = 0 to var i = 0 to prevent making i a global variable
for(var i = 0 ; i < 10 ; i++){//begin for loop
//append the URL GOTO assignment with the incremented variable
sample = "CODE:URL GOTO="+ variable++;
iimPlay(sample);
}//end for loop

Variable scope in javascript when iterating through a stack

I'm baffled. Could someone please explain to me why this produces an infinite loop?
var constant = 4;
var stack = new Array();
stack.push(0);
stack.push(1);
loop1();
function loop1(){
for(i = 0; i < constant; i++){
loop2(i);
}
}
function loop2(num){
for(i = 0; i < stack.length; i++){
console.log(i);
}
}
​
Fiddle: http://jsfiddle.net/elclanrs/tywV9
I suspect it has something to do with Javascript function-level variable scope, but that's as far as my guess goes.
When you don't declare a variable with the var keyword, the variable is global, so loop2 and loop1 are using the same (global) i variable. Every time loop2 is called, i gets set to 0 and then is incremented up to stack.length, which is 2. This means that every iteration of loop1 will end with i=2, which gets incremented to 3 but never reaches constant which is 4.
If you change your for loops to be for (var i = 0; ...) instead of for (i = 0; ...) then this should no longer loop infinitely.

Categories