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

The difference between const, var and let in js

高洛峰
Release: 2016-10-12 13:07:45
Original
1519 people have browsed it

The main content is: the differences between the three ways of defining variables in js: const, var, and let.

1. Variables defined by const cannot be modified and must be initialized.

const b = 2; // Correct

// const b; // Error, must be initialized

console.log('Const definition b outside function: ' + b); // There is an output value

// b = 5;

// console.log('Modify const definition b outside function: ' + b); //Cannot output

2. 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=1
function change(){
a = 4;
console.log('函数内var定义a:' + a);//可以输出a=4
} 
change();
console.log('函数调用后var定义a为函数内部修改值:' + a);//可以输出a=4
Copy after login

3.let is a block-level scope. After the function is defined using let, it has no impact on the outside of the function.

let c = 3;
console.log('函数外let定义c:' + c);//输出c=3
function change(){
let c = 6;
console.log('函数内let定义c:' + c);//输出c=6
} 
change();
console.log('函数调用后let定义c不受函数内部定义影响:' + c);//输出c=3
Copy after login


Related labels:
var
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