JavaScript for-loops are… complicated - HTTP203

What happens under the hood when we use for loop?

For loops are very simple, but interestingly it has gotten much more complicated in javascript. For example, let's examine a simple for loop code

for(var i = 0; i < 2; i++) {
    setTimeout(() => console.log(i)); 

In this example, the console will display just '2' two times, why? well, that is why you have to check out this video.

Var, Let and Const

What is the difference between var and let? What effect do they have? Check out this simple piece of code.

if(true) {
    var innerVar = 1;
    let innerLet = 1;
    const innerConst = 1;

The var is scoped to the parent function or global scope, const and let are lexically scoped to the block. So the first one will log '1', but the rest will cause an error.

So going back to the for loop, let's try it with a let,

for(let i = 0; i < 2; i++) {
    setTimeout(() => console.log(i)); 

This does magic tricks and will make you rethink what you thought of javascript, again just watch the video to be magical.

Subscribe for coding videos

Keep growing professionally with just three curated videos weekly.

We hate spam as much as you do.