DEV Community

Devraj Sawant
Devraj Sawant

Posted on

4. Let, Const and Var

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 
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

thank You!

Top comments (0)