I do know why const
doesn't work in for-loops. We need to create a new scope and copy over a value into that. So this won't fly.
for(const i = 0; i < 5; i++) console.log(i);
Whereas this will.
for(let i = 0; i < 5; i++) console.log(i);
However, I noticed that both of them work when looping though the properties of an object like this.
for(let property in thingy) console.log(property); for(const property in thingy) console.log(property);
I'm not sure why.
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).
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable.
The point of using const is creating immutable bindings instead of mutable ones. So you can't mutate the value stored in that variable.
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: If you use const for str in the above, you get an error:
Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true or false when analysed. A loop will continue running until the defined condition returns false.
While loops will run as long as the condition inside the ( ) is true. Example: while (condition) { code... } Spoiler Alert Solution Ahead! The do...while loop is closely related to while loop.
But this loop is seen to be very useful while working with objects. In each iteration, one of the properties of Object is assigned to the variable named variableName and this loop continues until all of the properties of the Object are processed. Lets take an example to demonstrate how for..in loop can be used to simplify the work.
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); }
This logs a
and b
, but if you change const
to var
, it logs b
twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With