The difference and recommended use of var, let, const

1. Function scope declaration using var --- variable promotion mechanism

When var is used to declare a variable, the variable is automatically added to the closest context. In a function: the closest context is the local context of the function; in a with statement, the closest context is also the function context; if a variable is initialized without being declared, it is automatically added to the global context.

function add(num1, num2){
    var num = num1 + num2
    return sum
}

let result = add(10, 20); // 30

console.log(sum) //报错,sum在这里不是有效变量

Here the function add defines a local variable sum to store the result of the addition operation. But the variable sum cannot be accessed outside the function. If the keyword var in the above example is omitted, then sum becomes accessible after add is called.

function add(num1, num2){
    num = num1 + num2
    return sum
}

let result = add(10, 20); // 30

console.log(sum)         //  30

This time, the variable sum variable is not declared with var. After calling add(), sum is added to the global context, and it still exists after the function exits, so it can be accessed later.

Summarize:

var declarations are brought to the top of the function or global scope, before all code in the scope. This phenomenon is called "hoisting". Hoisting allows code in the same scope to use it directly regardless of whether the variable has already been declared. In practice, however, ascension can also lead to legitimate but bizarre phenomena.

Initializing a variable without declaring it is a very common mistake in JavaScript programming and can cause many problems. For this reason, it is important to declare variables before initializing them. In strict mode, variables initialized without declaration will report an error

2. Use let's block-level scope declaration --- temporary dead zone (temporal dead zone) 

The new let keyword in ES6 is very similar to var, but its scope is block-level, which is also a new concept in JavaScript. Block-level scope is defined by the nearest pair of { }, such as: if block, while block, function block, and even a single block is also the scope of let declaration variables.

var a;
var a; // 不会报错,后声明都变量会覆盖先声明的变量

{
    let b;
    let b;
}  // SyntaxError : 标识符 b 已经声明过了

Look at the example above: another difference between let and var is that it cannot be declared twice in the same scope. Duplicate var declarations are ignored, and duplicate let declarations raise a SyntaxError 

for(var i = 0; i < 10; ++i){   }
console.log(i); // 10


for(let j = 0; j < 10; ++j){   }
console.log(j); // ReferenceError : j 没有定义

Look at the two examples above: the behavior of let is very suitable for declaring iteration variables in loops. Iteration variables declared with var leak outside the loop and should be avoided.

Summarize:

Strictly speaking, let is also hoisted at runtime in JavaScript, and you can't actually use a let variable before declaring it, simply because of the "temporal dead zone". So, from the point of view of writing JavaScript code, the hoisting of let is not the same as that of var.

Temporary dead zone: To sum it up in one sentence, it is a period of time between when the JavaScript engine enters the scope to create variables and when the variables start to be accessible, it is called TDZ.

3. Constant declaration using const

const a;  // SyntaxError : 常量声明时没有初始化

const b = 3;
console.log(b);  // 3
b = 4; TypeError : 给常量赋值

In addition to let, ES6 also added the const keyword. Variables declared using const must be initialized to a certain value at the same time. Once declared, they cannot be assigned new values ​​during their declaration cycle. In addition to following the above rules, const is the same as let declaration;

const o1 = {};
o1 = {};       // TypeError : 给常量赋值


const o2 = {};
o2.name = 'Barry';
console.log(o2.name); //  'Barry';


const o3 = Object.freeze({  });
o3.name = 'Barry';
console.log(o3.name);  // undefined

const declarations apply only to the topmost primitive or object. In other words, const variables assigned to objects cannot be reassigned to other reference values, but the keys of objects are not restricted;

If you want the entire object to be unmodified, you can use Object.freeze(), so that although you will not report an error when assigning a value to the property, it will fail silently;

4. Which one is more recommended for let  const

Development practice shows that if the development process will not be greatly affected by this, you should use const declarations as much as possible, unless you really need a variable that will be reassigned in the future. This can fundamentally ensure that bugs caused by reassignment are discovered in advance.

Guess you like

Origin blog.csdn.net/weixin_56650035/article/details/122633078