简体   繁体   中英

let declared variable can be declared or not

I am getting

Uncaught Syntax Error: Identifier 'a' has already been declared

can any one tell me why ?

 let a = 3; function a() { let a = 1; } console.log(a); a(); 

let makes a variable block scoped. All blocks opened within a block wherein a is declared know a .

Additionally, your first a and the function a are colliding.

Basically you did this:

let a = function () {
  let a = 1;
}

let a = 3; // At this point you already have 'a' variable

First of all, you're creating a function with the same name as an already created variable 'a', whether you can or not you really should never do that.

Secondly let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. In other words, your function already has the variable 'a' declared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM