The gym is opening online booking for the morning session. Bookings come through the old widget, booking-widget.js, written in 2014, and someone has to check it before it takes morning calls. Every variable in it is declared with var.
var was the only way to declare a variable before let and const arrived in 2015, so you’ll meet it in old code, answers, and tutorials. Here you’ll learn to read it and catch the bug it hides.
Read var as a Function-Wide Name
The widget’s bandFor() picks a wristband prefix. Written when booking was evening-only, it sets one only for the evening:
function bandFor(session) {
if (session === "evening") {
var prefix = "E";
}
return `${prefix}-101`;
}
console.log(bandFor("evening"));
The evening booking gets its band:
E-101
prefix is declared inside the if block, yet the return below it reads it. A let or const would be gone at the closing brace, because it belongs to its block. A var belongs to the whole function.
Python’s names behave the same way, so prefix assigned inside the if is visible after it: