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?
In your first code, you call the
console.log(x)before thexeven exists, because you define it first after theconsole.log(x). so there is no reference to anx.In your second code, you define the
xand then call theconsole.log(x)so yourxalready 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