Home >Web Front-end >JS Tutorial >Var Vs Let Vs Const

Var Vs Let Vs Const

Patricia Arquette
Patricia ArquetteOriginal
2024-11-23 20:20:14617browse

Var Vs Let Vs Const

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.

The above is the detailed content of Var Vs Let Vs Const. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn