The difference between var, let and const

wang xiao bo 's photo
wang xiao bo
·Dec 5, 2021·

3 min read

Subscribe to my newsletter and never miss my upcoming articles

Let's first understand the concept of hoisting.

console.log(b) // undefined
var= 1

From the above code, we can find that although the variable has not been declared, we can use the undeclared variable. This situation is called promotion, and the promotion is declaration.

In this case, we can look at the code like this

var b
console.log(b) // undefined= 1

Next, let's look at an example

var= 1var b
console.log(b)

For this example, if you think that the printed value is undefined, then you are wrong. The answer should be 10. For this case, let’s look at the code like this

var a
var a
a = 18
console.log(a)

In fact, not only variables will be promoted, functions will also be promoted.

console.log(a) // ƒ a() {}
function a() {}
var a = 1

The printed result will be ƒ a() {}, even if the variable is declared after the function, this also means that the function will be promoted and take precedence over variable promotion. Having said this, everyone must be aware of the problems with var. Variables declared with var will be promoted to the top of the scope. Next, let's look at let and const.

Let's first look at an example:

var a = 1
let b = 1
const c = 1
console.log(window.b) // undefined
console.log(window. c) // undefined

function test(){
  console.log(a)
  let a
}
test()

First, use let and const to declare variables in the global scope. Variables will not be mounted on window, which is different from var declaration. Furthermore, if we use a before declaring a, an error will occur

You might think that there has also been an improvement here, but for some reason it cannot be accessed. The first reason for the error is that there is a temporary dead zone. We can't use variables before declaration. This is also the point where let and const are better than var. Then there is a difference between the promotion you think and the promotion of var. Although the variable is told to be accessible in this scope during the compilation process, the access is restricted. So at this point, everyone must understand the difference between var, let and const. I don’t know if you have such a question, why there is promotion. In fact, the fundamental reason for promotion is to solve the situation where functions call each other.

function test1() {
    test2()
}
function test2() {
    test1()
}
test1()

If there is no promotion, then the above code cannot be implemented, because it is impossible for test1 to be in front of test2 and then test2 to be in front of test1.

 
Share this

Impressum

JavaScript Ruby on Rails