Javascript compiler error in Chrome's console

65 views Asked by At

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 the same Reference error but gave "Reference error : cannot access x before initialization". Why did the two compilers gave different errors?

2

There are 2 answers

0
pwoltschk On

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

5
Hassoo On

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 undefined.

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.