Main difference between var and let is Scoping.
var keyword:
var declare variable and optionally initialize the variable to a value.
Syntax:
var var1 [=value1] [, var2 [=value2]] ...;
var declarations, wherever it occur, are processed before any code is executed.
The scope of a variable declared with var
is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.
If you re-declare a JavaScript variable, it will not lose its value.
function reDeclareUsingVar() { var b = 11; var b = 22; console.log(b); // output is 22 }
if before declaring var if you try to use variable it will give the undefined output.
console.log(var1); // Output will be undefined var var1 = 11;
The scope of a JavaScript variable declared outside the function/block is global.
Example:
function variableDeclarationUsingJsVar(){ var var1 = 11; console.log(var1); // output 11 if(var1 === 11){ var var1=22; console.log(var1); // output 22 } console.log(var1); // output 22 }
let keyword:
let declares a block scope local variable, optionally initializing it to a value.
Syntax:
let var1 [=value1] [, var2 [=value2]] ...;
The scope of variable declared with let is to the nearest enclosing blocks.
if you re-declare a let variable, it will throw SyntaxError.
Example:
function reDeclareUsingLet() { let a = 11; let a = 22; // SyntaxError thrown console.log(a) }
Variables declared with let
are not accessible before they are declared in their enclosing block. and throw ReferenceError.
console.log(var2); // gives ReferenceError let var2 = 22;
The scope of a let variable declared outside the function/block is global.
Example:
function varDeclarationUsingLetKeyword(){ let var1 =11; console.log(var1); // output 11 if(var1 === 11){ let var1=22; console.log(var1); // output 22 } console.log(var1); // output 11 }
Why the keyword “let” selected is briefly explained at here.