-1

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.

Cody G
  • 8,368
  • 2
  • 35
  • 50
Manish Saraan
  • 167
  • 2
  • 14
  • You want to print all cities in the loop ? – Piotr Adam Milewski Jul 20 '17 at 16:38
  • Knowing what you're trying to do with current_city goes a long way toward giving you a better answer :) – trevdev Jul 20 '17 at 16:43
  • I dont want to print all the cities in loop. I am using them inside for loop. but i can print the current_city variable outside the for loop, which is strange to me. I just want to know why this is happening. – Manish Saraan Jul 20 '17 at 16:45
  • 1
    The behaviour is correct. For variable scoping u can refer this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types – Raghu DV Jul 20 '17 at 16:46
  • Note that if you use `let current_city = list[i];` (instead of `var`), then `current_city` will *not* be hoisted. It would be unavailable (and, I believe, throw a ReferenceError) outside the loop. – Paul Roub Jul 20 '17 at 16:50

3 Answers3

1

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);
}
jmargolisvt
  • 5,722
  • 4
  • 29
  • 46
1

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.
Cody G
  • 8,368
  • 2
  • 35
  • 50
0

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

Munawir
  • 3,346
  • 9
  • 33
  • 51