Variable declarations in js

Var declares variables

Declare variables inside functions

/** * message1 will be used as a global variable */
function test1() {
    message1 = 'Jump Code Education'
}
test1()
console.log(message1) // We can do this for you
Copy the code

Ps: Error example

The var declaration is not used inside the function

function test1() {
    message1 = 'Jump Code Education'
}
// The function declares variables internally. If var is not used, the variables become global variables
// After the function is executed, message1 becomes a global variable
test1()
console.log(message1) // We can do this for you
Copy the code

Function internal first, then var declaration

function test2() {
    console.log(auth)
    var auth = 'Jump Code Education'
}
// Variables declared inside a function with the var keyword are promoted to the top of the function scope
Test2 and test3 are equivalent
test2() //undefined
Copy the code

Equivalent sample

function test3() {
    var auth
    console.log(auth)
    auth = 'Jump Code Education'
}
Test2 and test3 are equivalent
test3() //undefined
Copy the code

Let declaration variable

The wrong sample

if (true) {
    let title = 'Hop Education -js variable scope'
}
console.log(title) //Uncaught ReferenceError: title is not defined

Copy the code

Temporary dead zone

Another important difference between let and VAR is that variables declared by let are not promoted in scope.

When parsing code, the JavaScript engine also notices the let declaration that appears after the block, but not in any way before

To refer to an undeclared variable. The moment of execution prior to a LET declaration is called a “temporal dead zone”, as shown here

A ReferenceError is raised when the phase refers to any variable declared later

Global declarations

Unlike the var keyword, variables declared with let in the global scope do not become properties of the window object (variables declared with var do)

var auth = 'Jump Code Education'
console.log(window.auth) / / education
let auth2 = 'Jump Code Education'
console.log(window.auth1) //undefined

Copy the code

A classic problem

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

  setTimeout(() = > console.log(i), 0)}Copy the code