JavaScript – Var-Let-Const

VarLetConst
Variable can be either Global Scope or Local ScopeVariable is Local scopeVariable is Local Scope
Re-Declaration or Updating of variable is possibleOnly Updating possibleNothing is possible.
Hoisting allowed – Variables initializes with “undefined”Hoisting allowed – Variables not initializes with values.Hoisting allowed – Variables not initializes with values.
Can be declared without being initializedCan be declared without being initializedMust be initialized with value at the time of declaration.

Clear explanation about Var, Let and Const:

Var: var declarations are globally scoped or locally scoped.

var x = 10;
function myFun() 
{
	var y = 20;
}

var variables can be re-declared:

var x = 10;
var x = 20;

Display the value of re-declared variable as follows:

var x = 10;
var times = 4;
if (times > 3) 
{
	var x = 20; 
}
console.log(x) // display 20

Hoisting of var: variables and function declarations are moved to the top of their scope before code execution.

Let: let is block scope. So a variable declared in a block with let  is only available within block.

let x = 10;
let times = 4;
if (times > 3) {
	let y = 20;
	console.log(y); // 20
}
console.log(y) // y is not defined
let can be updated:but not re-declared:
let x = 10;
x = 20;
let x = 10;
let x = 20; // error: already declared

However, if the same variable is defined in different scopes, there will be no error:

let x = "say Hi";
if (true) 
{
	let x = "say Hello instead";
	console.log(x); // "say Hello instead"
}
console.log(x); // "say Hi"

Hoisting of let: Just like var, let declarations are hoisted to the top. Unlike var which is initialized as undefined, the let keyword is not initialized. So if you try to use a let variable before declaration, you’ll get a Reference Error.

Const:

  • Variables declared with the const maintain constant values.
  • const declarations are block scoped
  • const cannot be updated or re-declared
const x = "say Hi";
x = "say Hello instead";// error: Assignment to constant variable.

Note: Every const declaration, therefore, must be initialized at the time of declaration.

Hoisting of const: Just like let, const declarations are hoisted to the top but are not initialized.

Scroll to Top