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.

4

4 Answers 4

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.

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);
}

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

-1

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

let b = 1;
var b1 = 2;
console.log(b);
console.log(b1);
1
  • I was looking for the riddle for step 3 not step 1 Commented Jan 12, 2018 at 6:46

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.