Difference between let and var in JavaScript

In JavaScript, letand varare both keywords for declaring variables, but they have some differences:

  • varIt is the way to declare variables in the ES5 standard, letbut it is a new way to declare variables in the ES6 standard.
  • varVariables declared are function-scoped or global-scoped, while letvariables declared are block-level scoped.
  • varA declared variable can be used before the variable is declared, and leta declared variable can be used only after the variable is declared.
  • varIf you use the keyword to declare an existing variable in the same scope, it will overwrite the previous variable; but if you use letthe keyword to declare an existing variable, an error will be thrown.
  • forUsing vara declared loop counter variable in a loop has variable hoisting, which can lead to unexpected behavior, whereas using a declared letloop counter variable does not.

Therefore, in general, it is recommended to letdeclare 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 vardeclared variables.

Guess you like

Origin blog.csdn.net/qq_29528701/article/details/131134092