Variable declarations , The essential syntax of every programming language , stay javascript in , The declaration of variables is relative to other languages , It's relatively simple .

Scope (Scope) What is it?

Scope is the execution environment of a program , It contains variables and functions that are accessible in the current location . stay ES5 In the syntax , There are global scope and local scope ,ES6 A new block level scope is added .

Global scope is the outermost scope , The variables defined outside the function belong to the global scope , Can be accessed by any other child scope . In the browser ,window Objects are global scopes . In the process of writing front-end code , One of the optimization rules is to use less global variables , Because global variables can easily lead to programs BUG, And it's not easy to find .

The basic unit of a local scope is function, It works only in function bodies . A local scope is a scope inside a function . Variables defined in a local scope can only be accessed in that scope and its child scopes .

javascript in , Variable declaration uses varconstlet To declare variables ,var by ES5 The grammar of ,const and let by ES6 After the grammar .ES6 Of let and const For newly introduced keywords , They will not be promoted , And block scope . That is to say, the variables declared by the area surrounded by braces will not be accessible outside .

Now let's talk about their differences .

var Statement

var Statement , by ES5 The grammar of ,var Declared variables always belong to the containing function ( That is, the overall situation , If it's on the top floor ). stay javaScript Variables declared within a function ( Use var) It's a local variable , So you can only access it inside a function ( The scope of this variable is local ). You can use local variables with the same name in different functions , Because only the function that has declared the variable can recognize the variable .

promote (Hoisting)

During the compilation process , take var and function The act of moving the definition of to the front of their scope is called ascension .

The entire function definition will be promoted . therefore , It can be called before the function has been defined , Don't worry about not finding the function .

console.log(toSquare(3)); // 9
function toSquare(n) {
    return n * n;

Variables are only partially elevated . And only the declaration of the variable is promoted , It doesn't move .

Developers may most want to implement for The block level scope of the loop , Because it's possible to restrict counter variables that you can declare at will inside the loop .

for (var i = 0; i < 10; i++) {

Executing functions immediately can effectively solve :

for (var i = 0; i < 10; ++i) {
    (function (value) {

Let's take another example

(function () {
    var testValue = "hello";
    var testFunc = function () {
        console.log("just test");
console.log(window.testValue); // undefined
console.log(window.testFunc); // undefined

Interesting topic :

var x = 10;
var y = 20;
[y, x] = [x, y];
console.log(x, y); // 20 10

let Statement

Premature visit let The reference to the declaration results in this referenceerror It's called temporary dead zone error , When accessing a declared but uninitialized variable . Create a block scope .

let g1 = "global 1";
let g2 = "global 2";
    g1 = "new global 1";
    let g2 = "local global 2";
    console.log(g1); // new global 1
    console.log(g2); // local global 2
    console.log(g3); // ReferenceError: g3 is not defined
    let g3 = "I am not hoisted";

const Statement

const It's locking the assignment , Don't lock the change of value . for example : Array 、 object . A common misconception is : Use const Declared variables , Its value cannot be changed , But for arrays and objects , Its value can be changed .

const tryMe = "initial assignment";
// The following reassignment will cause a program error
tryMe = "this has been reassigned"; // TypeError: Assignment to constant variable.
// For arrays, you can change element values
const array = ["Ted", "is", "awesome!"];
array[0] = "Barney";
array[3] = "Suit up!";
console.log(array); // [ 'Barney', 'is', 'awesome!', 'Suit up!' ]
// Change the entire array as follows , Relative to the reassignment , It's wrong.
array = ["Barney", "is", "awesome!", "Suit up!"];
//  Also for the object
const airplane = {};
airplane.wings = 2;
airplane.passengers = 200;
console.log(airplane); // { wings: 2, passengers: 200 }
// Here's the mistake
airplane = { wings: 2, passengers: 200 };

For support ES6 The grammar of , It is recommended to use... By default const, In variables that do need to be changed, declare the use of let, This makes the code immutable to some extent . So we can avoid many problems .