01. let和cost

2023-08-14 20:54:09发布
23

let

let关键字用于声明变量,和var不同点有 :

1. 变量不能重复声明

let name = 'tom'
let name = 'marry'

执行上面的语法控制台会提示错误 :Uncaught SyntaxError: Identifier 'name' has already been declared

2. let有块级作用域,var没有

{
    let name = 'tom'
}
console.log(name)

无法访问变量name

3. 不存在变量提升

console.log(name)    
let name = 'tom'

运行后报错 :Uncaught ReferenceError: Cannot access 'name' before initialization


const

const是用来定义常量的,除了有以下特点,别的和let一样 :

1.  用const来定义常量必须赋值

const name ; // 错误
const name = 'tom' // 正确

2. 定义好的常量值,后续不能在修改

const name = 'tom'
name = 'marry' // 错误

但是如果是常量是数组或者对象,修改里面的值是可以的。如 :

const nameList = ['marry', 'tom'];
nameList.pop();

或者

const Person = {
    name: 'tom',
    age: 18
}
Person.age = 20

3. 一般常量使用大写来定义(潜规则)

const NAME = 'tom'