skip to Main Content

I was doing some javascript coding in chrome’s console.

When I do:

console.log(x);
let x;

It gives "ReferenceError: x is not defined"

But when I run the below code:

let x;
console.log(x);

It consoles "undefined".

Q1: Why is it happening?

Q2: When I ran the first code in an online js compiler called OneCompiler, it didn’t give Reference error but gave "cannot access x before initialization". Why did the two compilers gave different errors?

2

Answers


  1. In your first code, you call the console.log(x) before the x even exists, because you define it first after the console.log(x). so there is no reference to an x.

    In your second code, you define the x and then call the console.log(x) so your x already exists and you get no error. But You have not assigned any value to your x. so x has the value "undefined". It is always like that in javascript. If you declare a variable without initializing it, the variable has the value "undefined"

    I hope this helps

    Login or Signup to reply.
  2. This is because of the concept of variable hoisting in javascript. In this code

    console.log(x);
    let x;
    

    the variable x gets "hoisted" to the top and since you havent declared a value to it you get the error ReferenceError: x is not defined.

    In the second code snippet, your approach is correct but since you have not defined x therefore you get an undefined error.

    Regarding your second question, it is possible that OneCompiler is using a different Javascript engine/implementation hence the difference in error but the underlying cause of the error is the same.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search