Var
var a = 11;
{
var a = 8;
};
console.log(a);// 8
-------------------------------------------------------------------------
var a = 11;
{
a = 28;
};
console.log(a);// 28
Variables declared with var are in the global scope. We can access a var variable even outside a block because it is not block-scoped. Additionally, we can redeclare and reassign a var variable both inside and outside a block.
Let
{
let a = 24;
}
console.log(a);// ReferenceError: a is not defined
-------------------------------------------------------------------------
{
let a = 24;
console.log(a);// 24
}
-------------------------------------------------------------------------
{
let a = 24;
a = 20;
console.log(a);// 20
}//
-------------------------------------------------------------------------
{
let a = 24;
let a = 20;
console.log(a);//SyntaxError: Identifier 'a' has already been declared
}
-------------------------------------------------------------------------
let a = 20;
{
let a = 24;
console.log(a);// 24
}
let has a separate memory space and block scope. Variables declared with let cannot be accessed outside the block because they are not in the global scope. We can reassign a let variable. However, we cannot redeclare the same variable within the same block, but we can redeclare it in a different block.
Const
{
const x = 4;
}
console.log(x);//ReferenceError: x is not defined
-------------------------------------------------------------------------
{
const x = 4;
console.log(x) ;// 4
}
-------------------------------------------------------------------------
{
const x = 4;
const x = 2;
}
console.log(x);//SyntaxError: Identifier 'x' has already been declared
-------------------------------------------------------------------------
{
const x = 4;
}
const x = 2;
console.log(x);// 2
-------------------------------------------------------------------------
const x = 2;// we can access the global(x)
{
const x = 4; // we cannot access the outside block
}
console.log(x);// 2
const has a separate memory space and is block-scoped. Once a value is declared and initialized with const, it cannot be redeclared or reassigned. We cannot access a const variable outside its block because it is not in the global scope. We cannot redeclare the variable within the same block, but we can redeclare it outside the block.
Top comments (0)