Home  >  Article  >  Web Front-end  >  When to use const keyword in JavaScript?

When to use const keyword in JavaScript?

藏色散人
藏色散人Original
2019-04-08 14:43:563672browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn