Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用let const var 声明变量的区别 #2

Open
nokelong opened this issue Mar 24, 2021 · 0 comments
Open

使用let const var 声明变量的区别 #2

nokelong opened this issue Mar 24, 2021 · 0 comments
Labels
JavaScript js基础

Comments

@nokelong
Copy link
Owner

nokelong commented Mar 24, 2021

let const 是ES6中新增的声明变量的关键字。
1、let
let 声明的变量具有如下特性:

  • 变量值在代码块有效,拥有块级作用域
  • 不存在变量提升
// let 的情况
console.log(b); // 报错ReferenceError
let b = 2;
  • 暂时性死域 ,let声明变量之前都不可用
if (true) {
  // TDZ开始
  tmp = 'abc'; // ReferenceError
  console.log(tmp); // ReferenceError
 
  let tmp; // TDZ结束
  console.log(tmp); // undefined
 
  tmp = 123;
  console.log(tmp); // 123
}
  • 不允许重复声明
  let a= 1;
  let a = 1;
// Uncaught SyntaxError: Identifier 'a' has already been declared

2、const
const 声明的变量具有如下特性:

  • 声明一个只读的常量,一旦声明,常量指向的内存地址不可改变
  • 简单类型数据Number,String,Boolean值不可改变
  • 复合类型数据Array,Object内存地址指针不可改变
  • 块级作用域,不存在变量提升
  • 不允许重复声明变量
const num = 10; 
num = 11; // Uncaught TypeError: Assignment to constant variable
const obj = {a: 1};
obj.b = 2;
console.log(obj); // {a: 1, b: 1}
<!--对obj 重新赋值-->
obj = {c: 3};  // Uncaught TypeError: Assignment to constant variable

3、var
var 声明的变量具有如下特性:

  • 允许重复声明变量
// var 的情况
var a =1;
var a = 2;
console.log(a); // 输出2
  • 变量存在变量提升,未声明前使用值为undefined
  • 作用域为定义的代码所在函数内
// var 的情况
console.log(a); // 输出undefined
var a = 2;
@nokelong nokelong added the JavaScript js基础 label Mar 24, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript js基础
Projects
None yet
Development

No branches or pull requests

1 participant