ECMAScript 2015: const in for loops
The following for-of loop works:
for (const e of a)
The ES6 specification describes this as:http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-in-and-for-of-statements-static-semantics-boundnamesForDeclaration : LetOrConst ForBinding
The imperative for loop will not work:
for (const i = 0; i < a.length; i += 1)
This is because the declaration is only evaluated once before the loop body is executed.http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-statement-runtime-semantics-labelledevaluation
for...of loop. Should I use const or let?
Why useIf there are no assignments to the identifier within the loop body, it's a matter of style whether you useconst
and when to uselet
infor...of
loops?
let
or const
.Use const
if you want the identifier within the loop body to be read-only (so that, for instance, if someone modifies the code later to add an assignment, it's a proactive error). Use let
if you want to be able to assign to it (because you have an assignment in your code, or you want someone to be able to add one later without changing the declaration).
You can do this with for-of
and for-in
loops. A for
loop's control variable is normally not constant (since in the normal case you update it in the "update" clause of the for
; if you don't, for
may be the wrong loop to use), so you normally use let
with it.
For clarity, here's an example with an assignment within the loop body:
for (let str of ["a", " b", " c "]) {
str = str.trim();
// ^^^^^----- assignment to the identifier
console.log(`[${str}]`);
}
Why can a for..of / for..in loop use const while a normal for loop can only use let or var for its variable in JS?
No the for(...of...)
loop won't get an error. Here is why:
In the second for loop, you are editing the constant variable which is NOT allowed. This throws a TypeError. In the first for loop, it doesn't matter what type of variable assignment you use. The variable (const
,let
, var
, or no identifier) calls on the iterator which creates a sort of isolated temporary scope. This is why you can't access the variable outside of the for loop. For example:
const example = 1;
example = 2;
//TypeError
for (const someVar of Array(5)) someVar = 12;
//TypeError
{
const num = 200;
}
const num = 150;
//This is fine because of scope
Why does const work in some for-loops in JavaScript?
for (const property in object)
works because with each iteration you get a new variable, which is scoped only to that iteration. You can easily check that by using a closure inside a loop:
for (const property in {a: 1, b: 2}) { setTimeout(() => { console.log(property); }, 100);}
Can for-loops counter be const declaration in ES2015?
I tested it (in Firefox) and the const binding works according to spec:
let i = 0;for (const len = 3; i < len; i++) { console.log(i);}
// From https://kangax.github.io/compat-table/es6/#test-constfor (const baz = 0; false;) {}
// Yay, a const counter! ...uhfor (const counter = {i: 0}; counter.i < 3; counter.i++) { console.log(counter.i);}
Using const as loop variable in for loop
It works in Stackblitz because it is running traspiled code:
AppComponent.prototype.test = function () {
var _loop_1 = function (i) {
setTimeout(function () {
console.log(i);
}, 100 * i);
};
for (var i = 0; i < 5; i++) {
_loop_1(i);
}
};
It won't work if you add a snippet here because it is not transpiledfor (const i = 0; i < 5; i++) { setTimeout(function() { console.log(i) }, 100 * i);}
Why JavaScript const works well with for in loop
By definition,Why JavaScript const works same as let in for in loop?
const
is block scoped like let
.It isn't. Since it is block scoped, each time you go around the loop the old constant drops out of scope and you create a new one.Then why the const num value getting updated in each iteration of the for in?
Why `const` value changed inside of `for...in` and `for...of` loop?
Every iteration of a loop has its own block scope.
for(let i = 0; i < 10; i++)
setTimeout(() => console.log(i), 1);
That creates 10 seperate scopes, thats why it logs 10 different numbers. Therefore you can also declare constants in these different scopes.
Related Topics
Arrow VS Classic Method in Es6 Class
JavaScript When to Use Prototypes
Check If an Object Implements an Interface at Runtime with Typescript
How to Remove a Table Row with Jquery
Adding Custom Http Headers Using JavaScript
Load "Vanilla" JavaScript Libraries into Node.Js
JavaScript Time Zone Is Wrong for Past Daylight Saving Time Transition Rules
How to Read JSON File with Fetch() in JavaScript
When Do I Need to Specify the JavaScript Protocol
Alternative or Polyfill for Array.From on the Internet Explorer
Why Does JavaScript's Regex.Exec() Not Always Return the Same Value
How to Auto-Reload Files in Node.Js
How to Read the Correct Time/Duration Values from Google Spreadsheet
In JavaScript, Can You Extend the Dom
How to Pull the File Name from a Url Using JavaScript/Jquery
Regular Expression | Leap Years and More
Fix the Upstream Dependency Conflict Installing Npm Packages