Home  >  Article  >  Backend Development  >  What is the difference between var and let/const in javascript?

What is the difference between var and let/const in javascript?

青灯夜游
青灯夜游forward
2019-01-04 18:02:093771browse

What is the difference between var and let/const in javascript? This article will introduce var and let/const to everyone, so that everyone can understand the difference between var and let/const. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. [Course Recommendation: JavaScript Video Tutorial]

What is the difference between var and let/const in javascript?

##let and const is a new command in ES6, used to declare variables. These two commands are many different from ES5's var, and there are also let and const There are some subtle differences, let’s take a look at them in detail below.

Content:

var and let/constThe difference

  1. Block-level scope

  2. There is no variable promotion

  3. Temporary dead zone

  4. Non-repeatable declaration

  5. Global variables declared by let and const will not be hung under the top-level object

constTwo points to note about the command:

  1. const must be assigned a value immediately after it is declared, otherwise an error will be reported

  2. const Once a 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, but the internal data can be changed.

Why do we need block-level scope?

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

This brings many unreasonable scenarios:

  1. Inner variables may overwrite outer variables

  2. used for counting The loop variable is leaked as a global variable

  3. var tmp = new Date();
    function f() {
      console.log(tmp); // 想打印外层的时间作用域
      if (false) {
        var tmp = 'hello world'; // 这里声明的作用域为整个函数
      }
    }
    f(); // undefined
    
    var s = 'hello';
    for (var i = 0; i < s.length; i++) {
      console.log(s[i]); // i应该为此次for循环使用的变量
    }
    console.log(i); // 5 全局范围都可以读到

Block-level scope

  1. scope

  2. function f1() {
      let n = 5;
      if (true) {
        let n = 10;
        console.log(n); // 10 内层的n
      }
      console.log(n); // 5 当前层的n
    }
  1. Block-level scope is nested arbitrarily

  2. {{{{
      {let insane = &#39;Hello World&#39;}
      console.log(insane); // 报错 读不到子作用域的变量
    }}}};
  1. Block-level scope is true Split the code into blocks

  2. {
    let a = ...;
    ...
    }
    {
    let a = ...;
    ...
    }
The above form,

can be used to test some ideas without worrying about duplicate variable names or external interference

Declaring functions in block-level scope:

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

Declare functions in block-level scope, preferably in the form of anonymous functions.

if(true){
  let a = function () {}; // 作用域为块级 令声明的函数作用域范围更清晰
}

The block-level scope of ES6 allows the rules for declaring functions, which is only true when curly braces are used. If curly braces are not used, an error will be reported.

// 报错
&#39;use strict&#39;;
if (true)
  function f() {} // 我们需要给if加个{}

There is no variable promotion

The phenomenon of variable promotion: In the same scope, variables It can be used before declaration. When the value is undefined

#ES5, use

var to declare the variable. Variable promotion often occurs.

// var 的情况
console.log(foo); // 输出undefined
var foo = 2;

// let 的情况
console.log(bar); // 报错ReferenceError
let bar = 2;

Temporary dead zone:

As soon as you enter the current scope, the variable you want to use already exists, but it is not available.

Only until the line of code that declares the variable appears can the variable be obtained and used

var tmp = 123; // 声明
if (true) {
  tmp = &#39;abc&#39;; // 报错 因为本区域有tmp声明变量
  let tmp; // 绑定if这个块级的作用域 不能出现tmp变量
}

The significance of temporary dead zone and inability to promote variables is:

In order to reduce runtime errors, prevent the variable from being used before it is declared, which may lead to unexpected behavior.

Repeated declaration of variables is not allowed

This situation occurs during testing:
var a= 'declaration'; const a = 'No error', this situation is because Babel did some processing during the conversion, and tested it in the browser console, and successfully reported an error

let,const It is not allowed to declare the same variable repeatedly in the same scope

function func(arg) {
  let arg; // 报错
}

function func(arg) {
  {
    let arg; // 不报错
  }
}

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 the node environment is:
  3. global

  4. #Global variables declared by var will be hung under the top-level object, but let and const will not be hung under the top-level object. For example, the following chestnut
  5. var a = 1;
    // 如果在 Node环境,可以写成 global.a
    // 或者采用通用方法,写成 this.a
    window.a // 1
    
    let b = 1;
    window.b // undefined

const command

  1. Once declared, must Assign value immediately

    let p; var p1; // 不报错
    const p3 = &#39;马上赋值&#39;
    const p3; // 报错 没有赋值

  2. const Once declared the value cannot be changed

    Simple type: cannot be changed

    const p = &#39;不能改变&#39;;
    p = &#39;报错&#39;

    Complex Type: variable pointer cannot be changed

    Consider the following situation:

    const p = [&#39;不能改动&#39;]
    const p2 = {
      name: &#39;OBKoro1&#39;
    }
    p[0] = &#39;不报错&#39;
    p2.name = &#39;不报错&#39;
    p = [&#39;报错&#39;]
    p2 = {
      name: &#39;报错&#39;
    }

    const所说的一旦声明值就不能改变,实际上指的是:变量指向的那个内存地址所保存的数据不得改动

    • 简单类型(number、string、boolean):内存地址就是值,即常量(一变就报错).

    • 复杂类型(对象、数组等):地址保存的是一个指针,const只能保证指针是固定的(总是指向同一个地址),它内部的值是可以改变的(不要以为const就安全了!)

      所以只要不重新赋值整个数组/对象, 因为保存的是一个指针,所以对数组使用的pushshiftsplice等方法也是允许的,你就是把值一个一个全都删光了都不会报错。

> 复杂类型还有函数,正则等,这点也要注意一下。

总结:

再总结一下,看到这些名词,脑子里应该会有对应的理解,如果没有的话,那可以再看看对应的内容。

var和let/const的区别:

  1. 块级作用域

  2. 不存在变量提升

  3. 暂时性死区

  4. 不可重复声明

  5. let、const声明的全局变量不会挂在顶层对象下面

const命令两个注意点:

  1. let可以先声明稍后再赋值,而const在 声明之后必须马上赋值,否则会报错

  2. const 简单类型一旦声明就不能再更改,复杂类型(数组、对象等)指针指向的地址不能更改,内部数据可以更改。

let、const使用场景:

  1. let使用场景:变量,用以替代var。

  2. const使用场景:常量、声明匿名函数、箭头函数的时候。

以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注php中文网相关教程栏目!!!

The above is the detailed content of What is the difference between var and let/const in javascript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete