In JavaScript, let
and var
are both keywords for declaring variables, but they have some differences:
var
It is the way to declare variables in the ES5 standard,let
but it is a new way to declare variables in the ES6 standard.var
Variables declared are function-scoped or global-scoped, whilelet
variables declared are block-level scoped.var
A declared variable can be used before the variable is declared, andlet
a declared variable can be used only after the variable is declared.var
If you use the keyword to declare an existing variable in the same scope, it will overwrite the previous variable; but if you uselet
the keyword to declare an existing variable, an error will be thrown.for
Usingvar
a declared loop counter variable in a loop has variable hoisting, which can lead to unexpected behavior, whereas using a declaredlet
loop counter variable does not.
Therefore, in general, it is recommended to let
declare variables with , because it avoids some common mistakes and block-level scope is more in line with people's intuition. But in some specific cases, such as declaring variables in the global scope, or when you need to share variables in multiple functions, you can use var
declared variables.