This is the third day of my participation in the August More text Challenge. For details, see: August More Text Challenge

var

  1. Var is only function scoped, not block scoped, and can declare global/local variables.
  2. Variables defined by var cannot be accessed across functions, but they can be accessed across blocks!
  3. Var defines variables that are not initialized with undefined, but no error is reported
  4. You can repeat the definition, and the later one will override the first one.
var a; console.log(a); //undefined //----------------------------------------- var a = 1; // The global variable console.log(a); // 1 function A(){ a=2; console.log(a); // local variable a: 2} a (); console.log(a); / / call A function, A function inside A modified value: 2 / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the var b = 1; var b=2; console.log(b); //2, the following declaration overrides the previous declarationCopy the code

const

  1. Block-level scope valid;
  2. constDeclared variables must not change value, which means that once a const is declared, it must be initialized immediately and cannot be left for later assignment.
  3. For variables of complex type, such as arrays and objects, the variable name does not point to the data, but to the address where the data is located.constThe command only guarantees that the address to which the variable name points is invariant, not that the data at that address is invariant, so you have to be very careful when declaring an object as a constant.
const a ; // The variable should be assigned as soon as it is declared. const b = 2; B = 3; b = 3; const names = []; Names = [1,2,3] // error, because the variable names to address cannot change, should always point to [] address!! [1,2,3] is not the same address as []Copy the code

let

  1. A let is block-level scoped. Once a function is defined internally, it has no effect on the outside of the function

  2. Variables defined by a let can only be accessed within the scope of a block, not across blocks, much less across functions

  3. You cannot declare variables in advance, otherwise an error will be reported

  4. Do not repeat the definition, otherwise an error will be reported

let a =1; console.log(a); Function A(){let A = 2; console.log(a); // local variable: 2} A(); Console. log(" after A() function is called, the value of A defined by let is changed inside the function "+ A); //------2----- var b=1; { let b=2; console.log(b); // 2 } console.log(b); //1 console.log(aaa); let aaa=1; // let p = 1; let p = 2; console.log(p); // If you repeat the definition, an error will be reportedCopy the code