Home >Web Front-end >JS Tutorial >The difference between const and var in js
In JavaScript, const and var are keywords used to declare variables. They have the following differences in scope, variability and initial value: Scope: const is only within the block-level scope in which it is declared. is valid, whereas var is valid throughout the function scope. Mutability: Once declared, a const variable cannot be changed, whereas a var variable can be reassigned. Initial value: const variables must be initialized when declared, while var variables do not need to be initialized, and the default value is undefined.
The difference between const and var in JavaScript
Start
const and var are two keywords used to declare variables in JavaScript. They have different behaviors regarding scope, mutability, and initialization.
Scope
Variability
Initial value
Other Differences
In addition to these main differences, there are some other differences between const and var:
When to use const and var
Example
<code class="javascript">// 使用 var 声明变量 var name = "John"; name = "Mary"; // 重新赋值 // 使用 const 声明常量 const PI = 3.14; PI = 3.15; // 错误:常量不可变</code>
Conclusion
const and var are two different ways to declare variables in JavaScript Keywords, which have clear differences in scope, mutability, and initial values. Understanding these differences is important for writing robust and maintainable JavaScript code.
The above is the detailed content of The difference between const and var in js. For more information, please follow other related articles on the PHP Chinese website!