I know a quick google search can yield some results. But I am really confused. Since there are really smart JS developers here I thought to ask anyway. A simple, easy to understand guide will be really helpful to me and others too.
const — constant. block-scoped. You can't assign a new value to a constant, although if constant is an object or an array you can change its properties and items.let — block-scoped. It exists only in current and descendant scopes.var — not block-scoped. It seems people avoid using var in modern JS.function () {
for (let l = 0;) {} // will be available inside the loop only
for (var v = 0;) {} // will be available outside the loop and inside the function scope
console.log(l) // l is not defined
console.log(v) // shows value of v after for is finished
}
const c = 0;
c = 2; // Error

Shreyansh Pandey
node, coffee and everything in between
Alright, so
constandletwas introduced in ES6. I have covered each of them in detail on my blog here.In short,
varis a way of setting the variables in JavaScript; however, the problem is the fact that JavaScript has something called Variable Hoisting. What it means is that the variable is scoped outside the base scope. It sounds really confusing, but what it really means is:x = 10; console.log( x ); var x;will be converted to, on interpretation:
var x; x = 10; console.log( x );Now, generally this is good, but it poses a problem when you use the variable with the same name in different scopes. Take the following example:
function someFunction() { var myVariable = 10; if( true ) { var myVariable = 20; console.log( "Value inside the block: " + myVariable ); } console.log( "Value outside the block: " + myVariable ); } someFunction();The value, in both the cases, will be
20. However, withconstandlet, the value ofmyVariablewithin theif-scopewill be 20, but outside that, it'll be10.You use
letfor general variables, andconstfor constants. Both have block-level scoping! :DIn the post, I mention again, I have covered this and all the new, cool features of ES6 extensively with examples; be sure to check it out! :)
I hope this helps!