This is the 18th day of my participation in Gwen Challenge


Interviewer: You know const, let and var. Tell me the difference

I:… πŸ’₯


preface

It can be said that this is the bank we interview the highest frequency of a question, but also a very basic question. Therefore, we must not be unclear on this issue, then send a thank-you note on the spot. πŸš€ Of course, we also need to learn more about the implementation of const and let.

let

The let keyword is used to declare variables. Variables declared using let have several characteristics:

  1. Duplicate declarations are not allowed;
  2. Block level scope (local variable);
  3. There is no variable promotion;
  4. The scope chain is not affected;
The sample
// An example of the let keyword:
let a; // Single declaration
let b,c,d; // Batch declaration
let e = 100 ; // Single declaration and assignment
let f = 521 , g = 'iloveyou', h = []; // Batch declare and assign values
Copy the code
Duplicate declarations are not allowed
let dog = "Dog";
let dog = "Dog";
// Uncaught SyntaxError: Identifier 'dog' has already been
declared
Copy the code
Block level scope (local variable)
{
let cat = "Cat";
console.log(cat);
}
console.log(cat);
Uncaught ReferenceError: cat is not defined
Copy the code
There is no variable promotion
// Let does not exist, var does exist;

console.log(people1); // The default value can be printed
console.log(people2); // ReferenceError: People2 is not defined
var people1 = "Eldest brother"; // There is a variable promotion
let people2 = "The second brother." "; // There is no variable promotion
Copy the code
Does not affect the scope chain:
// What is a scope chain: it simply means that a code block is within a code block, and a local variable in a superior code block is available to a subordinate, as in a normal programming language
		{
            let p = "Eldest brother";
			var s;               //p's scope is block-level (in curly braces), while s's scope is global
            function fn() {
                console.log(p); // We can use it here
            }
            fn();
        }
Copy the code
Application scenarios

Use let to declare variables later;

Let example: Click div to change the color
 // Get the div element object
        let items = document.getElementsByClassName('item');


        //ES5 error
        for (var i = 0; i < items.length; i++) {
            items[i].onclick = function () {
                items[i].style.background = 'pink'; 
                alert('Clicked' + i + 'δΈͺ')}// Since click events are asynchronous and I is global, each item uses the same I.

        }
        / / ES5 solution 1
        for (var i = 0; i < items.length; i++) {
            items[i].onclick = function () {
                this.style.background = 'pink'; // If you want to write it, you can write it
                alert('Clicked' + i + 'δΈͺ')}}/ / ES5 solution 1
        for (var i = 0; i < items.length; i++) {
            // Use closures to control scope
            (function (i) {
                items[i].onclick = function () {
                    items[i].style.background = 'pink'; / / write two
                    alert('Clicked' + i + 'δΈͺ')
                }
            })(i)
        }
        
        / / ES6 solutions
        for (let i = 0; i < items.length; i++) {

            items[i].onclick = function () {
                // Change the background color of the current element
                // this.style.background = 'pink'; // If you want to write it, you can write it
                items[i].style.background = 'pink'; / / write two
                It is important to note that the I in the for loop must be declared with let
                // If you use var, you will get an error because var is a global variable.
                // After the loop I will be 3 and items[I] will be indexed out of bounds
                // let is local variable
                // What we need to know is what value the I is when we click
                // The following declaration will overwrite the above, so the click event will find 3 every time
                // Since let declares local variables, each retains its original value
                // When you click the event call, you get the corresponding I}}Copy the code

const

The const keyword is used to declare constants. Const declarations have the following characteristics:

  1. Declare that an initial value must be assignedDE;
  2. Identifiers are generally capitalized (custom);
  3. Duplicate declarations are not allowed;
  4. The value cannot be modified;
  5. Block level scope (local variable);

Note: When a constant is an object, the value is not allowed to change

The sample
        // const declares a constant
        const DOG = "Prosperous wealth.";
        console.log(DOG);
        // 1. Declare that an initial value must be assigned;
        // const CAT;
        // Uncaught SyntaxError: Missing initializer in const declaration
        
        // 2. Identifiers are generally capitalized (custom);
        // const dog = "dog "; // Lowercase is good
        
        // 3. Duplicate declarations are not allowed;
        // const CAT = "meow meow ";
        // const CAT = "meow meow ";
        // declared: Uncaught SyntaxError: Identifier 'CAT' has already been declared
        
       // Note that changes to array elements and internal objects are allowed (arrays and objects store reference addresses);
        // 4. The value cannot be changed;
        // const CAT = "meow meow ";
        // CAT = "CAT ";
        // const arr = ['55','66'];
        // arr.push('77'); // '77' is already attached to arr because the address arr points to is not changed
        Uncaught TypeError: Assignment to constant variable
        
        // 5. Block level scope (local variable);
        / / {
        // const CAT = "meow meow ";
        // console.log(CAT);
        // }
        // console.log(CAT);
        Uncaught ReferenceError: CAT is not defined
  
Copy the code
Application Scenarios:

Declare the object type to use const, non-object type to choose let;

Var, let, and const

  1. Variables defined by var have no concept of blocks and can be accessed across blocks rather than functions. It’s not a global scope

  2. Variables defined by lets can only be accessed in the block scope, not across blocks or functions.

  3. Const is used to define constants, must be initialized (that is, must be assigned), can only be accessed in the block scope, and cannot be modified.

  4. Variables declared by var are promoted, while variables declared by let and const are not promoted (follow the “declare first, use later” principle, otherwise an error will be reported).

  5. Var does not have a temporary dead zone, while let and const do.

    Parsing: As long as the let command exists in the block-level scope, the variables it declares are bound to the scope without external influence.

  6. Var allows the same variable to be declared twice. Let and const are not allowed to declare the same variable in the same scope.

    Var allows a variable to be declared repeatedly, with the latter overwriting the former. Const and let will report an error.