In JavaScript and Scope IV - Blocks we showed that blocks on their own do not create a new scope when using the var keyword. Wouldn't it be nice if there were a way to create the toto variable inside a block so that it would have its own scope, unlike below?

var toto = 'wants' ; { var toto = 'a puppy' ; } console . log ( toto ) ;

ES6 allows block level scope with the let keyword when declaring variables.

var toto = 'wants' ; { let toto = 'a puppy' ; } console . log ( toto ) ;

In the code above, the toto variable inside the block no longer pollutes the value of the global variable because they are now two different variables even if they have the same name.

We can also fix the for loop example from the previous article.

var buzz = 3 ; for ( let buzz = 1 ; buzz < 10 ; buzz ++ ) { if ( buzz === 9 ) { console . log ( 'for loop buzz:' , buzz ) ; } } console . log ( 'global scope buzz:' , buzz ) ;

And we can also fix the if statement code. This time we use the const key word so the value cannot be changed.

var cute = 'not' ; if ( true ) { const cute = 'cat' ; } console . log ( cute ) ;