What is the difference between constants and variables in javascript

青灯夜游
Release: 2023-01-04 09:34:49
Original
3442 people have browsed it

Difference: Constants represent some fixed data, which must have an initial value, and the value cannot change during the running of the program; variables represent some changeable data, which may have no initial value, and Values ​​can change or be assigned again while the program is running.

What is the difference between constants and variables in javascript

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Variables

  • Variables represent some data that can change

  • Variables are containers used to store data and can change or be assigned again during the running of the program.

There are two ways to define variables, var and let (es6)

var variable name (old version before ES6)

// 定义一个变量
var a;
// 往变量中存储数据
a = 1;
// 从变量中取出存储的数据
console.log(a);
Copy after login

let variable name (ES6)

// 定义一个变量
let num;
// 给变量初始化
num = 2;
// 取出存储的数据
console.log(num);
Copy after login

Constant const

  • Constants represent some fixed data

  • Constants, like variables, are containers used to store data, but the value of the constant cannot change during the running of the program. Change.

There was no way to declare constants before ES6. In ES6, const was added to define constants.

const a = 1
Copy after login

Constants cannot be modified

const a = 1   //当常量a被创建时,再次给a赋值时,a仍为1
console.log(a);
a = 10;
console.log(a) // 报错
Copy after login

What is the difference between constants and variables in javascript

##Classification of constants

1. Integer constants

Integer constants are actually positive numbers. Any integer written in JavaScript is an integer constant

2. Real constants

Real constants are decimals

3. String constants

A string constant is actually the content enclosed in single quotes or double quotes. We call it a string constant

4. Boolean constant

Boolean constants are actually true or false, expressed through true and false in JavaScript

In JavaScript, Boolean constants have only two values, true (true) or false (false)

For more programming-related knowledge, please visit:

Programming Video! !

The above is the detailed content of What is the difference between constants and variables 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