Explain the difference between var / conlet and JavaScript variable declaration

Posted by ridgedale on Wed, 02 Feb 2022 02:56:40 +0100

Let and const are newly added commands in ES6 to declare variables. These two commands are different from var in ES5, and let and const are slightly different

The difference between var and let/const

  1. Block level scope
  2. There is no variable promotion
  3. Temporary dead zone
  4. Non repeatable declaration
  5. The global variables declared by let and const will not be hung under the top-level object

const command has two points to note:

  1. Value must be assigned immediately after const declaration, otherwise an error will be reported
  2. Once a const simple type is declared, it cannot be changed. The address pointed to by the pointer of a complex type (array, object, etc.) cannot be changed, and the internal data can be changed.

Why do I need a block level scope?

ES5 has only global scope and function scope, but no block level scope.

This brings many unreasonable scenarios:

  1. Inner variables may override outer variables
  2. The loop variable used to count is leaked as a global variable
var tmp = new Date();
function f() {
  console.log(tmp); // Want to print the time scope of the outer layer
  if (false) {
    var tmp = 'hello world'; // The scope declared here is the entire function
  }
}
f(); // undefined

var s = 'hello';
for (var i = 0; i < s.length; i++) {
  console.log(s[i]); // i should be the variable used in this for loop
}
console.log(i); // 5. It can be read globally

Block level scope

  1. Scope
function f1() {
  let n = 5;
  if (true) {
    let n = 10;
    console.log(n); // 10 inner n
  }
  console.log(n); // 5 n of the current layer
}
  1. Arbitrary nesting of block level scopes
{{{{
  {let insane = 'Hello World'}
  console.log(insane); // An error is reported, and the variable of the child scope cannot be read
}}}};
  1. Block level scope really breaks code into blocks
{
let a = ...;
...
}
{
let a = ...;
...
}

The above forms can be used to test some ideas without worrying about variable name duplication or external interference

Block level scope declaration function:

Declaring functions in the block level scope will cause some problems because the browser needs to be compatible with old code!

It is better to declare functions in block level scope in the form of anonymous functions.

if(true){
  let a = function () {}; // The scope is block level, which makes the scope of the declared function clearer
}

The block level scope of ES6 allows the rule of declaring functions only when braces are used. If braces are not used, an error will be reported.

// report errors
'use strict';
if (true)
  function f() {} // We need to add a {} to if

There is no variable promotion

Variable promotion: under the same scope, variables can be used before declaration, and the value is undefined

When using var to declare variables in ES5, the phenomenon of variable promotion often occurs.

// var situation
console.log(foo); // Output undefined
var foo = 2;

// let the situation
console.log(bar); // Error ReferenceError
let bar = 2;

Temporary deadband:

As soon as you enter the current scope, the variable to be used already exists, but cannot be obtained. You can obtain and use the variable only when the line of code declaring the variable appears

var tmp = 123; // statement
if (true) {
  tmp = 'abc'; // An error is reported because there are tmp declared variables in this region
  let tmp; // tmp variables cannot appear in the scope of binding if at the block level
}

The significance of temporary deadband and non variable promotion lies in:

To reduce runtime errors, prevent the variable from being used before it is declared, resulting in unexpected behavior.

Duplicate declaration of variables is not allowed

This happens during the test: var a = 'declaration'; const a = 'no error reporting'. This is because babel did some processing during conversion and tested it in the browser console, and then successfully reported an error

let and const are not allowed to declare the same variable repeatedly within the same scope

function func(arg) {
  let arg; // report errors
}

function func(arg) {
  {
    let arg; // No error reporting
  }
}

The global variables declared by let and const will not be hung under the top-level object

  1. The top-level object of the browser environment is window
  2. The top-level object of node environment is global
  3. The global variables declared by var will be hung under the top-level object, while let and const will not be hung under the top-level object. Like the chestnut below
var a = 1;
// In the Node environment, it can be written as global a
// Or use the general method to write this a
window.a // 1

let b = 1;
window.b // undefined

const command

  1. Once declared, the value must be assigned immediately

    let p; var p1; // No error reporting
    const p3 = 'Assign now'
    const p3; // Error report without assignment
  2. Once const is declared, the value cannot be changed

    Simple type: cannot be changed

    const p = 'Cannot change';
    p = 'report errors'

    Complex type: variable pointer cannot be changed

    Consider the following:

    const p = ['Cannot be changed']
    const p2 = {
      name: 'OBKoro1'
    }
    p[0] = 'No error reporting'
    p2.name = 'No error reporting'
    p = ['report errors']
    p2 = {
      name: 'report errors'
    }

    const says that once the value is declared, it cannot be changed. In fact, it means that the data stored at the memory address pointed to by the variable cannot be changed

    • Simple type (number, string, boolean): memory address is a value, that is, a constant (an error will be reported as soon as it changes)

    • Complex type (object, array, etc.): the address stores a pointer. Const can only ensure that the pointer is fixed (always pointing to the same address) and its internal value can be changed (don't think const is safe!)

      Therefore, as long as you do not re assign the entire array / object, because you save a pointer, the push, shift, splice and other methods used for the array are also allowed. You will not report an error if you delete all the values one by one.

    Complex types also include functions, regularities, etc., which should also be paid attention to.

Summary:

To sum up, when you see these nouns, you should have a corresponding understanding in your mind. If not, you can look at the corresponding content.

The difference between var and let/const:

  1. Block level scope
  2. There is no variable promotion
  3. Temporary dead zone
  4. Non repeatable declaration
  5. The global variables declared by let and const will not be hung under the top-level object

const command has two points to note:

  1. let can be declared and assigned later, while const must be assigned immediately after declaration, otherwise an error will be reported

  2. Once a const simple type is declared, it cannot be changed. The address pointed to by the pointer of a complex type (array, object, etc.) cannot be changed, and the internal data can be changed.

let and const usage scenarios:

  1. let usage scenario: variable to replace var.
  2. const usage scenario: constant, declaration of anonymous function and arrow function.

Topics: Javascript const let