1
头图

In JavaScript variables can use keywords to define var, let or const.

Before we can understand var , let and const before the difference, we need to understand a JavaScript concept scope.

scope essentially refers to the place where these variables are available.

Global scope

Variables declared globally have global scope outside of any function.

Global variables can be accessed from JavaScript program.

Local scope

Variables declared within a function have function scope.

Local variables can only be accessed from within the function in which they are declared.

Block scope

The code block is the code between the curly braces JavaScript Variables declared in block {} have block scope.

Note that var keyword cannot have block scope.

var

var declaration can be global or local (in a function).

When the var variable is declared outside the function, the scope is global. var is the function scope when it is declared in the function.

image

Variables declared with the var keyword can be redeclared like this

image

Or their values can be updated like this

image

let

let is now the first choice for variable declarations. This is not surprising, because it is an improvement var It also solves var , let us how to use it.

let is block-scoped, so the variable let declared in the block can only be used in this block.

image

Variables declared with the let keyword cannot be redeclared, it will throw such an error

image

let variables can be updated in their scope like this

image

constant

Use const maintain constant value declared variables. const statement has some similarities with the let Like the let declarations, the const declarations can only be accessed within the block in which they are declared.

image

But const can neither be re-declared nor re-assigned

image

image

finally

I hope this article can help you understand var , let and const . Thank you for your patience. If the article and notes can bring you a little help or inspiration, please don't be stingy with your Star and Fork. The article is continuously updated synchronously. You must be My biggest motivation to move forward😁


wscats
7.1k 声望13k 粉丝

分享和总结不易,求关注一下⭐️