This is the 26th day of my participation in The August More Wen Challenge.

Writing in the front

We use var, let, and const to define variables in our daily development. However, there are some differences between them.

The body of the

Variable ascension

Variables defined using var are automatically promoted to the top of the current scope, while let and const are not. See an example

var test = 'hello';
(function(){
    if (typeof test === 'undefined') {
        var test = 'juejin';
        console.log(test);
    } else {
        console.log(test);
    }
})()
Copy the code

What does this code output? The answer is Juejin.

The code first defines a variable called test and assigns it a value of Hello. Then it executes an immediate function. ‘, the declaration of test will be raised by JS to the top of the function, var test; We all know that if we define a variable without assigning a value, the value of the variable is undefined by default, so we use the type judgment here to get undefined, and then we assign the value of test to get the output result of juejin.

If the code is changed to the following, and the test variable is defined by let in the immediate execution function, then without the variable promotion, the test type will be determined by string, and the final output will be Hello.

var test = 'hello';
(function(){
    if (typeof test === 'undefined') {
        let test = 'juejin';
        console.log(test);
    } else {
        console.log(test);
    }
})()
Copy the code

Non-repeatable definition

Variables defined by let and const cannot be repeatedly defined, but let variables can be repeatedly assigned.

let a = 1;
a = 2;
console.log(2); / / 2

const c = 1;
c = 2; // Uncaught TypeError: Assignment to constant variable.
Copy the code

Const is used to define constants, but if const defines a constant of the Object data type, the value in that constant can be modified.

const obj = {
    a: 1.b: 2,
}
obj.a = 5;
console.log(obj); //{a: 5, b: 2}
Copy the code

conclusion

Of course, there are more differences between var, let and const than the above two points, but these two points are more important in daily development, friends can seriously experience, if interested in more in-depth study ~

The front end is long and long. We are all on the road. We hope to communicate with our friends and make progress together. Keep updating ing…..