您只需要 Javascript 备忘单!

var、let 和 const 之间的区别

1. var、let 和 const 概述

2. 范围差异

**例子:**

if (true) {
  var x = 10;
  let y = 20;
  const z = 30;
}
console.log(x); // 10 (accessible because of function scope)
console.log(y); // ReferenceError (block-scoped)
console.log(z); // ReferenceError (block-scoped)

3. 重新申报和重新分配

**例子:**

// Re-declaration
var a = 10;
var a = 20; // Allowed

let b = 30;
// let b = 40; // SyntaxError: Identifier 'b' has already been declared

const c = 50;
// const c = 60; // SyntaxError: Identifier 'c' has already been declared

// Re-assignment
a = 15; // Allowed
b = 35; // Allowed
// c = 55; // TypeError: Assignment to constant variable

4. 提升行为

**例子:**

console.log(a); // undefined (hoisted)
var a = 10;

console.log(b); // ReferenceError (temporal dead zone)
let b = 20;

console.log(c); // ReferenceError (temporal dead zone)
const c = 30;

5. let 和 const 之间的相似之处

6. 何时使用哪个?

7. 提升说明

什么是提升?

提升是 JavaScript 的默认行为,即在编译阶段将声明移动到其范围的顶部。

  • var:提升并初始化为未定义。
  • let / const:提升但未初始化。这会从块的开头到遇到声明为止创建一个暂时死区 (TDZ)。
  • 为什么提升以这种方式工作?

  • 编译阶段:JavaScript 首先扫描代码,为变量和函数声明创建内存空间。在此阶段:
  • var 变量被初始化为未定义。
  • let 和 const 变量被“提升”但未初始化,因此称为 TDZ。
  • 函数声明已完全提升。
  • 执行阶段:JavaScript 开始逐行执行代码。在此阶段,变量和函数被赋值。
  • 8. 吊装总结

    **例子:**

    // var
    console.log(foo); // undefined
    var foo = 10;
    
    // let
    console.log(bar); // ReferenceError
    let bar = 20;
    
    // const
    console.log(baz); // ReferenceError
    const baz = 30;

    结论

  • 对于不需要重新分配的变量,尽可能使用 const。
  • 对于需要在同一范围内重新分配的变量,使用 let。
  • 避免使用 var,除非使用遗留代码或需要函数范围的行为。
  • JavaScript 数据类型

    JavaScript 有各种数据类型,分为 **原始** 和 **非原始(引用)** 类型。下面通过示例和差异对每种类型进行解释:

    1.原始数据类型

    原始类型是不可变的,这意味着它们的值在创建后就无法更改。它们直接存储在内存中。

    2. 非原始(引用)数据类型

    非原始类型是可变的,并通过引用存储。它们用于存储数据集合或更复杂的实体。

    3. 原始类型和非原始类型之间的主要区别

    4. 特殊情况

    typeof 运算符

  • typeof null:由于 JavaScript 中的历史错误,返回“object”,但 null 不是对象。
  • typeof NaN:返回“数字”,即使它的意思是“非数字”。
  • typeof function:返回“function”,它是object的子类型。
  • 动态类型

    JavaScript 允许变量在运行时保存不同类型的值:

    let value = 10; // Number
    value = 'Ten'; // String
    value = true; // Boolean

    5. 每种数据类型的示例

    原始类型

    let str = 'Hello, World'; // String
    let num = 42; // Number
    let big = 123456789012345678901n; // BigInt
    let bool = true; // Boolean
    let notDefined; // Undefined
    let emptyValue = null; // Null
    let uniqueId = Symbol('id'); // Symbol

    非原始类型

    let obj = { name: 'John', age: 25 }; // Object
    let arr = [1, 2, 3, 4]; // Array
    let greet = function () {
      // Function
      console.log('Hello');
    };
    let today = new Date(); // Date
    let regex = /abc/; // RegExp
    let map = new Map(); // Map
    let set = new Set([1, 2, 3]); // Set

    6. typeof 结果总结