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.
Variables declared with the var
keyword can be redeclared like this
Or their values can be updated like this
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.
Variables declared with the let
keyword cannot be redeclared, it will throw such an error
let variables can be updated in their scope like this
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.
But const
can neither be re-declared nor re-assigned
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😁
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。