Photo by Claudio Schwarz on Unsplash
Understand var, let and const JavaScript like a ten year old
Variable declaration in JavaScript
After the release of ES6 version of JavaScript, a lot has changed. You also tend to differentiate programmers that have known JavaScript for a long time, and newbies through their use of the keyword, var.
The var has been the default way of declaring variables before ES6. It declares variables both from the global scope, and function scope. It is also good for hoisting (using a variable before it is declared).
ES6 brought to us some goodies, including new ways to declare variables i.e let and const.
The let is now preferred for variable declaration especially due to the fact that it is block scoped. It can also be re-declared or change its value during program execution.
The const is similarly different from the let. It is also block scoped. However, as its name implies, its value does not change during program execution. It strictly remains the same throughout the execution of the program.
Note: Scope: This implies where the variables are available to be used. It could b for the whole document or a function.
Global scope: A Globally scoped variable means it is available for use throughout the document or program.
Function scope means: A locally scoped or functionally scoped variable means it is available for use only in the function it is declared in.
Block scope: This means the variable is only available to be used within an enclosed curly brackets {}, e.g within an if statement, or switch, or a loop, etc.
Thank you for reading. I hope this helps in differentiating between var, let and const variables. Kindly check out my other articles and also follow me on twitter @jovialcoderr.