QUESTION: What is the difference between var, let, and const?
In modern JavaScript, there are three key ways to declare variables: var, let, and const. Understanding the differences between them is critical for writing predictable and high-quality code. Historically, variables declared with var appeared first. Their main feature is functional scope, which means the variable is accessible throughout the entire function where it was declared, regardless of code blocks. In addition, var is subject to hoisting and allows re-declaring the same variable within the same scope without throwing errors, which often leads to hard-to-find bugs.
With the advent of the ES6 standard, developers' arsenals were expanded with the let and const keywords, which introduce block scope. Variables declared with let are limited to the current code block enclosed in curly brackets and cannot be re-declared in the same scope, although their value can be changed during program execution. The const keyword works similarly to let by establishing block scope, but it imposes a strict limitation on reassigning the variable. It is important to note that if const is used with objects or arrays, the contents of the structure itself can be mutated by changing properties or elements, but assigning a reference to a new object is no longer possible. In modern development practice, it is recommended to use const by default for all immutable references, and to use let exclusively when the value of the variable is genuinely intended to be overwritten.