2

I have executed the following code and I found that I was unable to access the variable all the time in global scope.

 console.log(b); let b = 1;
VM12265:1 Uncaught ReferenceError: b is not defined
    at <anonymous>:1:13
(anonymous) @ VM12265:1
let b = 1; console.log(b);
VM12318:1 Uncaught SyntaxError: Identifier 'b' has already been declared
    at <anonymous>:1:1
(anonymous) @ VM12318:1
console.log(b);
VM12368:1 Uncaught ReferenceError: b is not defined
    at <anonymous>:1:13

I would like to know what happened to the variable b in step 3 once the step 1 and step 2 is executed.

kishorekumaru
  • 1,500
  • 2
  • 19
  • 33

4 Answers4

2

For the first one

console.log(b); let b = 1; VM12265:1 Uncaught ReferenceError: b is not defined at :1:13 (anonymous) @ VM12265:1

Let's binding is not created till they are initialized and hence no reference is created. You accessed the value in temporal zone


let b = 1; console.log(b); VM12318:1 Uncaught SyntaxError: Identifier 'b' has already been declared at :1:1 (anonymous) @ VM12318:1

For the second one, as the message says, b has already been declared already. As per spec

It is a Syntax Error if the BoundNames of BindingList contains any duplicate entries.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

let does not define variables for the global scope. You can declare let variable once at the beginning of the block scope and set the variable to a new value without attempting to re-declare the variable using let more than once to avoid error

{
  let b;

  try {
    console.log(b);
    b = 1;
    console.log(b);
    b = 2;
  } catch (err) {
    console.error(err.message)
  }
  console.log(b);
}
guest271314
  • 1
  • 15
  • 104
  • 177
0

You haven't declared variable b

2 ways:

  1. use var instead of let (That is because of JS Hoisting)

  2. declare b first then use it after

Xin
  • 33,823
  • 14
  • 84
  • 85
-1

I have checked in both the cases its working for me.

let b = 1;
var b1 = 2;
console.log(b);
console.log(b1);
cs95
  • 379,657
  • 97
  • 704
  • 746