var vs let vs const
No fluff lets get directly into it !
var vs let vs const
Declaration
var: Can be re-declared even after declaring it once !let: Cannot be re-declared ! Only one declaration per block !const: Same aslet!
Mutability
var: Mutable. Means will let you change values of variables,let: Mutable. Same asvarwill let you change values of variables.const: Immutable. Won't let you change values of variables declared usingconst!
Scopes
var: Function Scoped !
function scopeOfVar(){
var x = 8;
console.log(x);
}
scopeOfVar();
console.log(x); //ReferenceError: x is not defined
x is defined inside the function, hoisted to the top of the scope (the function in this case) and is not accessible outside of the function.
BUT....
for(var x = 0; x <= 3; x++){
console.log(x);
}
console.log("x after loop: ", x);
Loops wont create a specific scope for var variables therefore its hoisted to the top of the global scope in this case and is accessible even outside the for loop !
let: Block Scoped !
{
let x = 3;
console.log(x);
}
console.log(x); //ReferenceError: x is not defined
Here I defined a blank scope and declared x using let, since let is block scoped it will only be accessible inside that block ! And this applies for loops too...
for(let x = 0; x <= 3; x++){
console.log(x);
}
console.log("x after loop: ", x); //ReferenceError: x is not defined
Its only limited to the scope of the particular block where its defined !
const: Block Scoped !
{
const x = 3;
console.log(x);
}
console.log(x); //ReferenceError: x is not defined
Literally the same concept as let ! The only difference is of mutability !
const x = 15;
x = 79; //TypeError: Assignment to constant variable.
That's it ! You cannot change the value assigned to x at initialization !
Check out JavaScript Functions.