The difference between const, var, let in js

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

1 const b = 2;//correct
2 // const b; // error, must be initialized
3 console.log('outside the function const definition b:' + b);//There is an output value
4 // b = 5;
5 // console.log('Modify const definition b outside the function:' + b);//Cannot output

2. The variable defined by var can be modified. If it is not initialized, it will output undefined and no error will be reported.

copy code

1 var a = 1;
2 // var a;//No error
3 console.log('The var definition outside the function a:' + a);//You can output a=1
4 function change(){
5 a = 4;
6 console.log('The var defines a in the function:' + a);//Can output a=4
7 }
8 change();
9 console.log('After the function is called, var defines a as the modified value inside the function:' + a);//Can output a=4

copy code

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

copy code

1 let c = 3;
2 console.log('let definition outside the function c:' + c);//output c=3
3 function change(){
4 let c = 6;
5 console.log('let definition c:' + c);//output c=6
6 }
7 change();
8 console.log('After the function is called, the let definition c is not affected by the internal definition of the function:' + c);//output c=3

copy code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325065954&siteId=291194637