The var keyword is used to declare a new variable and optionally assign a value to it. This variable can be updated, and it has scope and hoisting. Variables declared with var are function-scoped, meaning they exist within the function in which they are declared. The problem with global declarations is that they can also be accessed outside of the function if they are declared globally, causing confusion and problems.
The const keyword, as its name implies, creates a constant variable that cannot be reassigned to a new value. Although the object properties can be updated or added, the general understanding is that the variable itself is immutable. This makes const a useful keyword for storing values that are intended never to change.
I want to point out that when a variable is declared inside a function, it can only be accessed within that function, creating a local scope. Variables declared inside curly braces, such as those in if statements, switch conditions, and/ or loops, are known as variables within block scope.
Block scope variables are not accessible outside the block in which they are declared.
However, hoisting is also commonly associated with var declarations, even though they are not technically hoisted in the same way as function declarations. When a var declaration is hoisted, only the declaration itself is moved to the top of the scope, not the assignment or initialization of the variable. This can lead to unexpected behavior and errors if not handled properly.
If you are still scratching your head, like I did when I first bumped into the term of hoisting, I will bring a little more light. I like analogies, so I will use a plumber toolbox as an example.
Let’s say that the plumber’s toolbox is a bit disorganized, and sometimes tools get hidden underneath others. When this happens, the plumber may not see the tool it needs and must search for tools.