js中多let与var

在 JavaScript 中,letvar 都用于声明变量,但它们有一些关键的区别。主要区别包括作用域、变量提升、可重复声明、以及在全局作用域中的行为。

1. 作用域(Scope)

  • let :块级作用域。用 let 声明的变量只在其所在的代码块 { ... } 中有效。

    { let x = 10; } console.log(x); // ReferenceError: x is not defined

  • var :函数级作用域。用 var 声明的变量在函数内可用,但如果在函数外声明,则它是全局变量。

    { var y = 20; } console.log(y); // 20

2. 变量提升(Hoisting)

  • let:存在"暂时性死区"(Temporal Dead Zone),即变量在声明前不能访问。虽然在内存中存在,但访问会导致错误。

    console.log(a); // ReferenceError: Cannot access 'a' before initialization let a = 5;

  • var :会被提升至作用域顶部,因此可以在声明之前访问,但值为 undefined

    console.log(b); // undefined var b = 5;

3. 重复声明(Redeclaration)

  • let:在同一作用域内不允许重复声明同一变量。

    let c = 1; let c = 2; // SyntaxError: Identifier 'c' has already been declared

  • var:允许在同一作用域内重复声明。

    var d = 1; var d = 2; // No error, d is now 2

4. 全局作用域中的行为

  • let :在全局作用域中声明时不会成为 window 对象的属性。

    let e = 10; console.log(window.e); // undefined

  • var :在全局作用域中声明时会成为 window 对象的属性。

    var f = 10; console.log(window.f); // 10

相关推荐
小小测试开发4 小时前
安装 Python 3.10+
开发语言·人工智能·python
KaMeidebaby5 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl6 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl6 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
AAA大运重卡何师傅(专跑国道)6 小时前
【无标题】
开发语言·c#
nuIl6 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl6 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf6 小时前
Python 异常处理
前端·后端·python
sugar__salt6 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
XBodhi.6 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio