Home > Web Front-end > JS Tutorial > The difference in usage between var, let and const in js

The difference in usage between var, let and const in js

巴扎黑
Release: 2017-07-22 15:38:26
Original
2058 people have browsed it

The difference between var, let and const in js

The main content is: the difference between const, var and let, the three ways to define variables in js.
Variables defined by var can be modified. If not initialized, undefined will be output and no error will be reported.
var a = 1;// var a;//不会报错console.log('函数外var定义a:' + a);//可以输出a=1function change(){a = 4;console.log('函数内var定义a:' + a);//可以输出a=4} change();console.log('函数调用后var定义a为函数内部修改值:' + a);//可以输出a=4
Copy after login
var is divided into two types: local scope and function scope

let is a block-level scope. After let is defined inside the function, the No effect outside the function.
let c = 3;console.log('函数外let定义c:' + c);//输出c=3function change(){let c = 6;console.log('函数内let定义c:' + c);//输出c=6} change();console.log('函数调用后let定义c不受函数内部定义影响:' + c);//输出c=3
Copy after login
let is a block-level scope. Different from var, let has no pre-function and cannot be repeatedly declared.

Variables defined by const cannot be Modified and must be initialized.
const b = 2;//正确// const b;//错误,必须初始化 console.log('函数外const定义b:' + b);//有输出值// b = 5;// console.log('函数外修改const定义b:' + b);//无法输出
Copy after login
const is a constant, cannot be changed, is generally uppercase, and is also a block-level scope. . .

The above is the detailed content of The difference in usage between var, let and const in js. 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