2

I am reading Nodejs API, and I confused with iteration of buffer:

for (const b of buf10) {
  console.log(b)
}

const is used to declare constants, so why use const instead of let?

Borkes
  • 181
  • 1
  • 2
  • 11
  • 1
    const simply means that the identifier wont be reassigned. – Nodir Rashidov Jun 21 '17 at 07:18
  • 1
    cant do `const variable = "something";` `while(true) {variable = "something else";}` when i know that i will not reassign the variable (eg when i create an instance of an object) i use const. Every other occasion let is used – Nodir Rashidov Jun 21 '17 at 07:20
  • possible duplicate - https://stackoverflow.com/questions/21237105/const-in-javascript-when-to-use-it-and-is-it-necessary – Kaushik Jun 21 '17 at 07:25

2 Answers2

6

Because b is a constant in the loop scope. Remember that let and const have block scope in ES6. Every iteration does create a new variable which will stay constant in its scope.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

const is used to declare constants, so why use const instead of let?

Because you can either use var let or const for declaration purpose however they behave differently.

In this case,

for (const b of buf10) {
  console.log(b)
}

Works because for each iteration you are getting a new const b and ending after the current iteration.

Concluding that if you know before hand that you are not going to modify the variable inside loop scope, you can go for it safely.

You'll see an error if you try to modify the b inside the loop.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Yeah! I use the closure test, `const` and `let` work different from `var`: `let a = []; for (const b of buf10) { a.push(function(){ log(b); }) }` `let b = []; for (var c of buf10) { b.push(function(){ log(c) }) }` – Borkes Jun 21 '17 at 07:46
  • @Borkes Hope you saw the different values for b even inside closure where others end up in same value – Suresh Atta Jun 21 '17 at 07:51
  • results are different of a and b, array of b has same value not a. @Suresh Atta – Borkes Jun 21 '17 at 07:55