php中文网

let、var 或 const 之间有什么区别?

php中文网

使用 var 关键字声明的变量的作用域为创建它们的函数,或者如果在任何函数外部创建,则为全局对象。 let 和 const 是块作用域的,这意味着它们只能在最近的一组花括号(函数、if-else 块或 for 循环)内访问。

function foo() {
  // all variables are accessible within functions.
  var bar = 'bar';
  let baz = 'baz';
  const qux = 'qux';

  console.log(bar); // bar
  console.log(baz); // baz
  console.log(qux); // qux
}

console.log(bar); // referenceerror: bar is not defined
console.log(baz); // referenceerror: baz is not defined
console.log(qux); // referenceerror: qux is not defined

if (true) {
  var bar = 'bar';
  let baz = 'baz';
  const qux = 'qux';
}

// var declared variables are accessible anywhere in the function scope.
console.log(bar); // bar
// let and const defined variables are not accessible outside the block they were defined in.
console.log(baz); // referenceerror: baz is not defined
console.log(qux); // referenceerror: qux is not defined

var 允许变量被提升,这意味着它们可以在声明之前在代码中引用。 let 和 const 不会允许这样做,而是会抛出错误。

console.log(foo); // undefined

var foo = 'foo';

console.log(baz); // referenceerror: can't access lexical declaration 'baz' before initialization

let baz = 'baz';

console.log(bar); // referenceerror: can't access lexical declaration 'bar' before initialization

const bar = 'bar';

用var重新声明变量不会报错,但let和const会报错

var foo = 'foo';
var foo = 'bar';
console.log(foo); // "bar"

let baz = 'baz';
let baz = 'qux'; // uncaught syntaxerror: identifier 'baz' has already been declared

let 和 const 的区别在于 let 允许重新分配变量的值,而 const 则不允许。

// This is fine.
let foo = 'foo';
foo = 'bar';

// This causes an exception.
const baz = 'baz';
baz = 'qux';

以上就是let、var 或 const 之间有什么区别?的详细内容,更多请关注php中文网其它相关文章!