const were not introduced yet. A variable created with the
var keyword will either be functionally or globally scoped depending on where it was declared. Using this type of variable will give you the freedom of being able to reassign the value if needed. I personally try to avoid using the
var keyword because you are able to declare the same variable as many times as you like and basically the last assigned value becomes the data stored within the variable. Also, no errors are thrown as well, so it can be difficult to figure out the discrepancies in your code without any feedback.
let keyword is similar to
var, but you could say it’s a more updated version of
var with better uses. Unlike
var, these types of variables are block-scoped which means that they can be used both in the block they are declared and also in any nested blocks.
Let does allow you to reassign the value later on if you like, just as
var does, but it will not let you declare the same variable more than once in the same block of code. Luckily, if this does happen by mistake, a syntax error will be thrown, explaining that the variable had already been declared so it makes for an easy fix.
const keyword creates a variable that, like its name implies, has a value that stays constant and cannot be reassigned. If you try reassigning the same
const variable with the
const keyword, you will get a syntax error saying that the identifier has already been declared. And if you try reassigning it without a keyword, you will get a type error so it is easy to keep track of if a mistake is made. Like
const variables are also block-scoped so the same rules apply in terms of where they can be referenced.
var keyword in my code to practice better programming patterns since
const are now it’s new and improved replacement.
Let me know if you found this helpful in deciphering between the different variable keywords in the comments!