For rainy days …

I am not a big fan of JavaScript, because it is very error prone. Unfortunately, if you wish to write a quick WebUI there is currently no other option.

Here a is a quick snippet of code:

let x = "x0";
console.log(x);
if (x.length !== 0) {
  console.log(x);
  let x = "x1";
  console.log(x)
}

What is the output of this code?

Please try to understand the code first, before reading the explanation bellow.






Scenario 1: Nothing is wrong with this …

x0
x0
x1

But this answer is wrong …

Scenario 2: Something is wrong …

x0
undefined # or ReferenceError: if you run this with node
x1

Note: Node crashes with a ReferenceError on the second console.log, but this code runs fine in the browser.

Even if it is not obvious, this is a classic case of variable shadowing in JavaScript. In JS variable scope is bound to a block of code, even if its declaration comes after the reference line, therefore a ReferenceError error may be raised. These kind of errors are incredibly annoying to debug in JS.