[Js] js in const, var, let the difference

1.const defined variables can not be modified, you must initialize (otherwise error).

const b = 2; // correct 
// const b; // error must be initialized 
console.log ( 'outer const function definition b:' + b); // the output value // B =. 5; // Console. log ( 'const modify definitions outside the function b:' + b); // can not be output

2.var defined variables can be modified, will not initialize output undefined, it does not complain.

Copy the code
Var A =. 1. 1; 
2 // var A; // not given 
3 console.log ( 'function definition outer var a:' + a); // can be output. 1 = A 
. 4 Change function () { 
. 5 A = . 4; 
. 6 the console.log ( 'the function defined var a:' + a); // can be output. 4 = a 
. 7} 
. 8 Change (); 
. 9 the console.log ( 'var defined function call after a modification value as a function of the internal : '+ a); // may output a = 4
Copy the code

3.let block-level scope is, let the internal function definitions used, no effect on the external function.

Copy the code
Let C =. 3. 1; 
2 the console.log ( 'external function definition let c:' + c); // output. 3 = C 
. 3 Change function () { 
. 4 let C =. 6; 
. 5 the console.log ( 'let the function definition of c: '+ c); // output. 6 c = 
. 6} 
. 7 Change (); 
. 8 the console.log (' defines the internal function is not affected by the definition of the function call let c: '+ c); // output c = 3
Copy the code

If wrong, please correct me!

Guess you like

Origin www.cnblogs.com/htybky/p/11521880.html