JavaScript101:Variable Declaration

JavaScript101:Variable Declaration

01:Types of Variables

  • Var

var keyword is used to declare variables in JavaScript that are mutable and have function scope.

Here is an example of using the var keyword in JavaScript:

var x = 5;
console.log(x); // Output: 5
x = 7;
console.log(x); // Output: 7
        

In this example, the variable x is declared using the var keyword and is assigned the value of 5. Later, the value of x is changed to 7. Since var variables are mutable, this is allowed.

  • Let

let is a keyword used to declare variables in JavaScript that are block-scoped and can be reassigned.

let x = 5;
console.log(x); // Output: 5
x = 7;
console.log(x); // Output: 7
        

In this example, the variable x is declared using the let keyword and is assigned the value of 5. Later, the value of x is changed to 7. Since let variables are mutable, this is allowed. However, unlike var variables, let variables are block-scoped, meaning they only exist within the block they are defined in.

  • Const

The const keyword in JavaScript is used to declare variables that cannot be reassigned.

const x = 5;
console.log(x); // Output: 5
x = 7; // This will result in an error
console.log(x);        

In this example, the variable x is declared using the const keyword and is assigned the value of 5. Since const variables cannot be reassigned, attempting to change the value of x to 7 will result in an error. const variables are also block-scoped, like let variables, and only exist within the block they are defined in.

Difference between Let/Const/Var

No alt text provided for this image


  • Var is function-scoped, can be reassigned, and can be redeclared.
  • let is block-scoped, can be reassigned, and cannot be redeclared.
  • const is block-scoped, cannot be reassigned, and cannot be redeclared.


Mail Your Articles on JavaScript to get featured

[email protected]


要查看或添加评论,请登录

社区洞察

其他会员也浏览了