JavaScript: Var, Let & Const

Photo by Sincerely Media on Unsplash

In JavaScript programming, and other languages as well, variables are used to hold specific values so that they can be referenced at a given time based on the scope they are in. A variable itself is simply an abstracted vessel to store a value which can range from numbers, strings, arrays, objects, functions, etc. They allow flexibility in creating applications by letting the developer reference the variable instead of the actual data it represents. Depending on the type of variable, the value can be reassigned or expanded upon based on how they are utilized in the program. When writing in JavaScript, there are three different kinds of variable keywords that can be implemented which are , and .

The keyword was used more commonly before the JavaScript ES6 version was released since and were not introduced yet. A variable created with the 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 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.

The keyword is similar to , but you could say it’s a more updated version of with better uses. Unlike , 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. does allow you to reassign the value later on if you like, just as 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.

The 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 variable with the 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 , variables are also block-scoped so the same rules apply in terms of where they can be referenced.

The new rollout of JavaScript ES6 in mid 2015 has permanently changed the way developers can use variables in their applications. I have made it a point to not use the keyword in my code to practice better programming patterns since and 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!

Full Stack Software Engineer |