Home > Web Front-end > JS Tutorial > body text

When to use const keyword in JavaScript?

藏色散人
Release: 2019-04-08 14:44:34
Original
3682 people have browsed it

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) // 未捕获引用错误
Copy after login

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');
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!