DEV Community

Kaziu
Kaziu

Posted on

📦 loop and block scope. difference between var and const with image

At first basic for loop

for(let i = 0; i < 5; i++) {
  const num = i * 2
  console.log(num)
}

// 0 2 4 6 8
Enter fullscreen mode Exit fullscreen mode

const can't reassign neither redeclare, but there is no any error.
So block scope might change each time

▼ then add setTimeout in this loop

for(let i = 0; i < 5; i++) {
  const num = i * 2
  setTimeout(function() {
    console.log(num)
  }, 1000)
}

// (after 1s)
// 0, 2, 4, 6, 8
Enter fullscreen mode Exit fullscreen mode

If I use var ?

for(let i = 0; i < 5; i++) {
  var num = i * 2 // ⭐ var !!!!
  setTimeout(function() {
    console.log(num)
  }, 1000)
}

// (after 1s)
// ⭐⭐ 8 8 8 8 8 
Enter fullscreen mode Exit fullscreen mode

Why result is "8 8 8 8 8" ??
Because declare var in block scope is the same as declare var as global scope. var doesn't have block scope

Image description

//⭐ declare var in block scope is the same as like this
var num; 
for(let i = 0; i < 5; i++) {
  num = i * 2
  setTimeout(function() {
    console.log(num)
  }, 1000)
}

// (after 1s)
// 8 8 8 8 8 
Enter fullscreen mode Exit fullscreen mode
  • var

num changes(overwrite) 8 after 1ms when setTimeout() executes

Image description

  • const

num declares each time loop, so even though the name num is the same, save in different memory places

Image description


ref. from this course

(note for myself)
var: setTimeout()が実行される1秒後には、numはもう8になっとる。var numはglobalなので、上書きされマッセ

const: loopごとに宣言されてます。numって名前一緒じゃけど、違うメモリスペースにありマッスル

Top comments (1)

Collapse
 
gilfewster profile image
Gil Fewster • Edited

Nice one.

I can't resist adding an example with both global and function-scoped var declarations to really illustrate the difference side-by-side.

// cats has global scope. it can be
// accessed from anywhere in this file
// including from inside functions
var cats = 5;

function doubleCats () {
  // moreCats has function scope. it can't
  // be accessed by anything outside this function
  var moreCats = cats * 2;
  return moreCats;
}

console.log(cats) // 5
console.log(doubleCats()) // 10
console.log(moreCats) // error: 'moreCats is not defined'
Enter fullscreen mode Exit fullscreen mode

The example above shows that var scope can go down (eg from global into function) but not back up (from function out to global).


Note for beginners following along

Accessing a global variable from within a function, the way doubleCats is doing here by accessing cats, is generally a bad idea. If your function requires external data, the preferred method would be to pass the data as an argument.

My code above accesses the global var directly just to demonstrate how a globally scoped var can be accessed from a function block. Whether it should be accessed in this way is another question entirely.

A more robust version of this function would look like this:

function doubleCats (currentCats) {
  var moreCats = currentCats * 2;
  return moreCats;
}
Enter fullscreen mode Exit fullscreen mode

And, since we're being pedantic...

The moreCats var is also unnecessary. Again, it's just an opportunity to show that the function-scoped variable cannot be accessed from outside of the function. In the real world, we'd just return the result directly without storing it in a variable:

function doubleCats (currentCats) {
  return currentCats * 2;
}
Enter fullscreen mode Exit fullscreen mode