Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

JavaScript let vs var vs const

We define variables in JavaScript using let, var, or const. In this article let us explore each of them and find out the difference between let vs var vs const. Knowing the difference between them is makes it easier to decide what to use where and when.

Using Let, Var & Const

The following example shows how to declare a variable using the let var & const keywords. You can create variables without an initial value

                            
var message1;
let message2;
 
//const does not support creating a variable without initial value.
                            
                            
                        

or you can create them with an initial value.

                            
var message1 ="Hello"
let message2 ="hi"
const message3= "Hello World"
                            
                            
                        

Difference between Let vs Var vs Const

Variable Scope

The scope or visibility of the variable is the major difference between these keywords.

The scope is a region of the program where a variable is visible. Every variable we define will become part of a scope. We can access that variable only within its scope.

JavaScript creates fourScopes. They are Global Scope, Function Scope, Block Scope & Module Scope.

We can access the variable only inside the scope in which we declare it. We cannot access it outside the scope

var is function scoped

The variables we declare using var inside a function are only available within that function. If we declare them outside the function, then they are available everywhere i.e. they are a global variable.

Even if we declare a var variable inside a code block, they are still scoped to the enclosing function. If there is no enclosing function, then they will become a global variable.

For Example, in the following code. variable localVar is declared inside the if block, but you can refer to it anywhere inside the function in which it is defined. That includes nested functions or other code blocks. But you cannot refer to it outside the function.

                            
function someFn() {   
 
 if (true) {        

   //defined locally
   //Its scope ends where curly braces ends

   var localVar=1000
   console.log(localVar)      //ok
 }

 console.log(localVar)        //ok

 function nested() {         
   console.log(localVar)      //ok
 }

}

console.log(localVar)      //erro
                            
                            
                        

let & const are block scoped

The variables declared using let or const are block-scoped. They are scoped to the block in which we declare them. A code block is anything inside curly parentheses. For Example, if condition, try/catch/ block, while loop, for loop, function, etc. keyword. They are local to the code block in which we declare them. must be specified along with the declaration.

This means that we can only use it in the code block where we declare them. Outside the code block, they are invisible

If they are outside the code block, but within the function body then they become function scoped.

If they are outside the function and code block, then they are available globally or become a global variable.

For Example, change the variable type of localVar to let. You will JavaScript immediately throws an error in all instances where they are outside the if block.

                            
function someFn() {   
 if (true) {        

   //defined locally
   //Its scope ends where curly braces ends

   let localVar=1000
   console.log(localVar)      
 }

 console.log(localVar)        //error

 function nested() {         
   console.log(localVar)      //error
 }

}

console.log(localVar)      //error
                            
                            
                        

We can redeclare a var variable

We can redeclare or redefine a var variable.

For Example, here we are declaring MaxTry variable twice. The JavaScript does not complain and the code works perfectly. Note that we even changed the value from number to string.

                            
var MaxTry=10;
console.log(MaxTry);
 
var MaxTry="hundred";     //No Error here even if we are declaring it again
console.log(MaxTry);
 
                            
                            
                        

But we cannot use the let or const to redeclare a variable.

The following example tries to redeclare a variable that is already declared with var. Identifier 'MaxTry' has already been declared is thrown by JavaScript here

                            
var MaxTry=10;
console.log(MaxTry);
 
let MaxTry="hundred";     //Uncaught SyntaxError: Identifier 'MaxTry' has already been declared
console.log(MaxTry);
                            
                            
                        

The same goes if you try to redeclare a let variable with var

                            
var MaxTry=10;
let MaxTry=10;
console.log(MaxTry);
 
var MaxTry="hundred";     //Uncaught SyntaxError: Identifier 'MaxTry' has already been declared
console.log(MaxTry);
                            
                            
                        

Var can be accessed before they are declared

We can access the var variable, even before we declare them.

This is because the JavaScript compiler process all variable declarations before executing any code. Hence declaring a variable anywhere in the code, is equivalent to declaring it at thetop of the scope . This is called variable hoisting.

                            
console.log(testVar);    //undefined
var testVar="hello";
 
 
                            
                            
                        

Now, change var to let. Compile and run the code. The code throws an error

                            
console.log(testVar);    //ReferenceError: testVar is not defined
let testVar="hello";
                            
                            
                        

Const cannot be reassigned

We must declare a const variable with an initial value. The value cannot be reassigned again.

          
const MaxTry=10 ;
MaxTry=5;            //Error 
        
        
    

Global Variables

If we declare a variable outside the scope, then it will become a global variable.

                              
let glet = "Global let";
var gVar = "Global var";
 
console.log(glet)    //Global let
console.log(gVar)    //Global var
 
                            
                            
                        

But there is a difference in how JavaScript creates them.

The global variable using the var keyword becomes property of the global object. The name of the global object in the browser environment is window. You can also access the global object using the propertyglobalThis . Hence we can use global object to access any global variable created by var keyword.

But global variables using the let (or const) keyword does not become the property of the global object. Hence we cannot access them using the global object

                              
var gVar = "Global var";
 
 console.log(gVar)              //Global var
 console.log(globalThis.gVar)   //Global var
 console.log(window.gVar)       //Global var
  
  
 let glet = "Global let";
 console.log(glet)             //Global let
  
 //The following codes does not work 
 console.log(globalThis.glet)  //Undefined
 console.log(window.glet)      //Undefined
 
                            
                            
                        

let, var & const. Which one to choose?

Now, we know the difference between let, var & const. So the question is which one will you choose.

Const is always the first choice, if the value of the variable does not change once initialized. This will prevent some programmers from accidentally modifying the value, which can happen if you use var or let

let is the choice of all other variables. Because let & const are block-scoped. You do not have to worry about variables declared in for loop or if the statement is overwritten outside the block. block scope helps us to identify bugs and makes our code easier to read.

Avoid var. The var can be redefined, can be reassigned, and does not support block scope. This makes the code harder to read & debug.

Read More

  1. JavaScript Tutorial
  2. JavaScript Hello World Example
  3. Syntax and Rules
  4. JavaScript Identifiers
  5. Keywords & Reserved Words
  6. JavaScript Variables
  7. Constants in JavaScript
  8. Let, var & const
  9. Data Types in JavaScript