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
In your first code, you call the
console.log(x)
before thex
even exists, because you define it first after theconsole.log(x)
. so there is no reference to anx
.In your second code, you define the
x
and then call theconsole.log(x)
so yourx
already exists and you get no error. But You have not assigned any value to yourx
. 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
This is because of the concept of variable hoisting in javascript. In this code
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.