I have been playing with ES6 for a while and I noticed that while variables declared with var
are hoisted as expected...
console.log(typeof name
ES6
introduces Let
variables which comes up with block level scoping
. Until ES5
we did not have block level scoping
, so the variables which are declared inside a block are always hoisted
to function level scoping.
Basically Scope
refers to where in your program your variables are visible, which determines where you are allowed to use variables you have declared. In ES5
we have global scope,function scope and try/catch scope
, with ES6
we also get the block level scoping by using Let.
var
keyword, it's known the entire function from the moment it's defined.When you define a variable with let
statement it's only known in the block it's defined.
function doSomething(arr){
//i is known here but undefined
//j is not known here
console.log(i);
console.log(j);
for(var i=0; i
If you run the code, you could see the variable j
is only known in the loop
and not before and after. Yet, our variable i
is known in the entire function
from the moment it is defined onward.
There is another great advantage using let as it creates a new lexical environment and also binds fresh value rather than keeping an old reference.
for(var i=1; i<6; i++){
setTimeout(function(){
console.log(i);
},1000)
}
for(let i=1; i<6; i++){
setTimeout(function(){
console.log(i);
},1000)
}
The first for
loop always print the last value, with let
it creates a new scope and bind fresh values printing us 1, 2, 3, 4, 5
.
Coming to constants
, it work basically like let
, the only difference is their value can't be changed. In constants mutation is allowed but reassignment is not allowed.
const foo = {};
foo.bar = 42;
console.log(foo.bar); //works
const name = []
name.push("Vinoth");
console.log(name); //works
const age = 100;
age = 20; //Throws Uncaught TypeError: Assignment to constant variable.
console.log(age);
If a constant refers to an object
, it will always refer to the object
but the object
itself can be changed (if it is mutable). If you like to have an immutable object
, you could use Object.freeze([])