Home >Web Front-end >JS Tutorial >When to use const keyword in JavaScript?
In this article, we will introduce to you how to use the const keyword instead of the var keyword in JavaScript. (Recommended: "javascript tutorial")
const
: In JavaScript, if we use the const keyword to declare a variable, we cannot use the const keyword as an identifier for the variable. Reassign.
const
keyword is block scope and we will also see an error if we try to access any variable before initialization.
var: If we use the var keyword to declare a variable, we can reassign the variable identifier.
What is an identifier?
The name we use to identify a variable is called an identifier.
Let's look at some examples.
const keyword usage example
const name = "reactgo.com"; // 我们不能把新值赋给const变量 name = "king" //类型错误:赋值给常量变量。 //块作用域 if(true){ const hello = "hello world" console.log(hello) // "hello world" } //我们不能在块范围之外访问变量hello。 console.log(hello) // 未捕获引用错误
We cannot reassign any new value to the const keyword variable identifier, but we can modify it using keys and array values Object, as shown in the following example.
const user = { name: "example1", age: 5 } // 我们不能分配一个新对象 user = { } user.name = "example2"; const colors = ['red','green','blue','yellow']; //我们不能分配一个新的数组 colors = [ ] colors[0] = "olive" colors.push('orange');
This article is an introduction to the use of const keywords in JavaScript. It is simple and easy to understand. I hope it will be helpful to friends in need!
The above is the detailed content of When to use const keyword in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!