var, let & const how to use them

Rule 1: var is define in the scope of your function.

Rule 2: let is define in the scope of your block.

Rule 3: var is also define in the scope your block.

Then when inspecting your html page you have the following result :

There is no error for the second console.log because of rule 1.

If i replace var by let we now have an error :

function sayHello() {
    for (let i = 0; i < 5; i ++) {
        console.log('a : ', i};
    }
    console.log('b :', i)
}

The difference between rule 2 and rule 3 is that when you have a const variable you can’t re assigned a value to your variable, because it’s a constant.

const x =  1; 
x =  2; 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.