使用let和const声明变量和常量

使用let和const声明变量和常量

一、let:声明一个变量

1)let声明的变量没有提升(let声明的变量也没提升,仅仅是没有初始化)

console.log(a); let a = 110; // Cannot access ‘a’ before initialization

2)let 配合 {} 也可以形成块级作用域

if(true){
var a = 110; // 全局变量
// b只能在当前的{}中被访问到 出了块就访问不了
// let b = 666; // let + {} 形成块级作用域
// }
// console.log(b); // b is not defined

3)使用let声明的变量不会挂载到GO上

let a = 110;
console.log(window.a); // undefined 访问一个对象上没有属性,得到的就是und

4)使用let不能重复声明

let a = 1;
let a = 2;
console.log(a); // Identifier ‘a’ has already been declared

记住:不要使用var来定义变量(使用var声明变量代码执行时有提升,比较复杂); 使用let声明变量

二、const:是声明一个常量

const a = 110; // 定义了一个常量(不会改变的量)
a = 666;
console.log(a); // TypeError: Assignment to constant variable.

1)也没有提升
console.log(a);
const a = 1; // Cannot access ‘a’ before initialization

2)也会形成块级作用域:
if(true){const a = 111;}
console.log(a); // a is not defin

3)使用const声明的常量不会挂载到GO上
const a = 1;
console.log(window.a); // undefin

4)使用const不能重复声明
const a = 1;
const a = 2;
// Identifier ‘a’ has already been declared
console.log(a);

5)const在声明常量时,必须赋值
const a;
a = 1;
console.log(a); //SyntaxError: Missing initializer in const declaration

再次提示:声明变量使用let 声明常量使用const 不要用var
看个例子:function sum(a) { console.log(a); const a = 100; console.log(a); }//这里因为a不能重复定义,所以语法错误,语法错误代码直接不执行,显示Uncaught SyntaxError: Identifier ‘a’ has already been declared
sum(200)

       console.log(b);
       const a = 100;
       console.log(a);
   }
   sum(200)```//200 100
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值