Javascript Variables Confusion

Can you explain why these two are producing different output

var x = 5;
console.log(x);
console.log(y);

and

var x = 5;
console.log(y);
console.log(x);

Both of the code are giving reference error as expected. But the first program printing 5 then giving reference error, as it’s not able to find variable y in it’s scope.
But the second code is giving reference error then terminating the code. Why the console.log(x) line not being executed in the second case ? Does javascript stops where it finds an error ?

yes, an error stops the execution of the code

there are ways to avoid the code from stopping once an error is met, you can read about that starting from this page, the second half titled Exception handling statements

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling

1 Like

Alright ! I got it . Thanks :slight_smile: