Today, I met the variable defined by const for the first time. I checked the relevant data and sorted out this article. The main content is: the difference between const, var and let, the three ways of defining variables in js.

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

 const b = 2;  // correct const b;  // Error, must initialize Console. log ('const definition outside the function b: '+b)// With output value b = 5; Console. log ('Modify the const definition outside the function b: '+b)// Unable to output

2. Variables defined by var can be modified. If they are not initialized, they will be output undefined without error.

 var a = 1; var a;  // No error reporting Console. log ('var definition outside the function a: '+a)// Can output a=1 function change(){ a = 4; Console. log ('var definition in function a: '+a)// Can output a=4 }  change(); Console. log ('After the function is called, var defines a as the internal modified value of the function: '+a)// Can output a=4

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

 let c = 3; Console. log ('function external let definition c: '+c)// Output c=3 function change(){ let c = 6; Console. log ('let definition in function c: '+c)// Output c=6 }  change(); Console. log ('let definition c after function call is not affected by function internal definition: '+c)// Output c=3

This article is reproduced on cnblogs: http://www.cnblogs.com/ksl666/p/5944718.html

Last modification: November 6, 2017
If you think my article is useful to you, please feel free to appreciate it