We all know var,const and let are used for declaring variables, but why do we have 3 keywords for the same task? Let’s find out.
VAR:
Before ES6 was introduced, there was only one way of declaring variable and that was 'var'
but the problem was 'var' was function scope and not block scope
Function Scope
Function scope is basically the var can be accessed anywhere in the function, no matter in which scope{} it is written
function abc() {
{ var x = 10 }
console.log(x); // it works even tho x was declared in scope
}
this caused accidental variable leaks causing further bugs
to resolve this Issue, CONST and LET was introduced in ES6
CONST & LET
Both Const and Let was introduced in ES6
Both were Block scope
No redeclaration in same scope
Both are similar but the only and main difference is
Const value cannot be changed and reassigned
however Let can be reassigned value as many time as we want
- Const are better for storing API_KEYS and other values which will stay constant
- Let can be used in Loops and temporary data storage
let score = 0;
score += 10;
console.log(score); // 10
const PI = 3.1416;
thank You!
Top comments (0)