var
存在变量提升,而let,const
不存在变量提升+ 什么是变量提升
+ 在javascript中,函数及变量声明都将被提升到函数的最顶部
+ 在javascript中,变量可以在使用前声明也可以在使用后声明
console.log(a); // undefind ===> a已经声明但是没有辅助
var a = 100;
console.log(b); // 报错:b is not defind 找不到变量
let b = 200;
console.log(c); // 报错:c is not defind 找不到变量
const c = 300;
function fun() {
// 在else 中的声明变量 a 将提升到最顶部
// console.log(a) // undefind
// console.log(b) // b is not defined
// console.log(c) // c is not defined
if(true) {
console.log(a)
console.log(b) // ReferenceError: Cannot access 'b' before initialization 不能在变量声明前使用 b
console.log(c) // ReferenceError: Cannot access 'c' before initialization 不能在变量声明前使用 c
var a = 1;
let b = 2;
const c = 3;
console.log(a) // 1
}
}
console.log(a) // ReferenceError: a is not defined 变量提升不会突破函数内部
let,const
都是块级局部变量{
let a = 1;
// 变量 a 超出大括号将使用将报错
}
console.log(a) // a is not defined
// const 与 let 一样 区别在于 const 在声明时就需要赋值
const b // 报错:SyntaxError: Missing initializer in const declaration
// 另外不同的是 const 赋值后 再次赋值将报错
const c = 100
c = 200
const num = 1;
num.b = 2; // 不会报错 num.b 的值也无法访问
console.log(num.b) // undefined
let, const
不能声明同名变量,而var可以const a = 2
const a = 1
// Identifier 'a' has already been declared 变量 a 已经被声明
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。