Summary: In this tutorial, you will learn the reason let and const which are ES6 feature came into existence in 2015 after var and when you should use them.
Today we will be looking into problems
const are solving and how we can use them effectively in our code going forward.
without any further ado,
What are variables?
Variables, in a nutshell, are containers, which can hold something for us, and return the things kept in them whenever they are been called upon.
let us see a variable like a labeled plastic thin container, which we can store our seasonings like salt, milk, sugar, and Maggi in our kitchen for easier access
If a stranger is asked to go and bring a plastic thin labeled Sugar from several plastic thin containers, it will be easier to locate since they are all labeled and that's basically what variables are, nothing more.
what you store (value) in your thin container (variable) and the label (name) you give to it is left to you to decide.
You can put your salt in a milo container and still tell the stranger that the container labeled milo is for salt, and everything will still go well, as far as you and the stranger remember what the container contains.
But definitely, something will go wrong if, for some reason we one day mistook the milo salt container for the real milo or sugar, this is the more reason our variable name must describe the information represented by the variable. A variable name should tell you or anyone specifically in words what the variable stands for.
So what is var, const, and let?
These three keywords are just a way of saying "hey Sam, use the milo thin as a salt container", Sam in this context is the interpreter that tells the browser to allocate or create a new memory address called milo and store salt in it, and that's it.
Their syntax is as follow
// syntax for using var var miloContainer = "salt"; // syntax for using let let miloContainer = "salt"; // syntax for using const const miloContainer = "salt";
Terms in variables:
- Variable Declaration and
- Variable Initialization
1. Variable Declaration:
// Keep a space for me to park my car
This is the process whereby you declare a container for later use, using either var, const, or let, it's just like saying, "Hey Sam, I will be keeping the car keys in that yellowContainer soon".
By that, a declaration has been made, you can also see it as reserving a container for something.
// declaring an empty variable with var var saltContainer; // declaring an empty variable with let let sugarContainer; // declaring an empty variable with const const maggiContainer; // something will happen here soon
we are telling the browser to create these variables in its memory location and that we will be sending their values soon, while a container without content is called an empty container, a variable without a value is referred to as a variable with undefined.
undefined is the default value of a declared variable without a value
2. Variable Initialization:
// I am here with my car, where is my space?
Since variable declaration is the act of keeping space for later use, initialization is the process of assigning or putting a value into the declared variable, which then means our container is not empty anymore.
add the following code to the previous example
// assigning a value to the empty variable declared with var saltContainer = "salt"; // assigning a value to the empty variable declared with let sugarContainer = "sugar"; // assigning a value to the empty variable declared with const maggiContainer = maggi; // this will throw an error when you assign a value to it
Oops, there is an error with the const, don't frick out, explanation ahead
you don't need to always declare and initialize a variable later.
you can declare and initialize a variable at once
// declaration ----- initialization var saltContainer = "salt";
Now that we have learnt about the common method of variables, let us move ahead and discuss about the generations of variables.
What do I mean by this?
We both know to this point that var, const and let is used to create a new variable/container, but the way var was designed, it allows anyone to change the label of our container, even when it is unintentional, imagine someone changing the label of your salt container to sugar before your new cook arrived or the amount you transferred to a client was accidentally deducted by the machine before getting to its destination account. I hope you get the gist.
In a real-world implementation, this is bad and can cause unexpected errors and results.
let's learn by doing, copy the code snippet below and run it
// create a new variable called name and store "Samuel" in it var name = "Samuel"; // somewhere in our 1120 line of code, forgotten we've used name as a variable var name ="Your name"; // expected result is Samuel console.log(name)
your console output will be "Your name" even though we expected to see "Samuel", if such happens in a financial application like bank receipt or during a money transaction, somebody might get fired.
in a nutshell var allows us to change the current value of a variable, and it's difficult to debug in some cases.
The main problem with var is what we called re-declaration and re-initialization of variables, it allows us to change the value of a container and also allows us to redeclare existing variable names.
var saltContainer = "salt"; // re-declaring and re-initializing an existing variable var saltContainer = "sugar"; console.log(saltContainer) // guess the output -sugar
in one sentence:
const is the opposite of var
Yes, const was designed and implemented in a way to serve as an alternative to var, const does not allow re-declaration and re-initialization of variables.
const saltContainer; // this will throw an error saltContainer = "salt"; console.log(saltContainer);
const sugarContainer = "whiteSugar"; const sugarContainer = "BrownSugar"; console.log(sugarContainer);
the error this will throw is
Identifier 'sugarContainer ' has already been declared
`const we do not have to bother about changing our application variable values by accident.
I know at this point you might be thinking that since the problem we have with the
var keyword has already been solved by the implementation of the
const keyword, then what is left for the
let keyword to solve 🤷♀️🤷♀️🤷♀️.
const keywords once more, remember that the
var keyword allows us to re-declare and re-initialize our variables, while the
const keyword does not support re-declaration and re-initialization of our application variables, right?.
But in a case where we want to re-initialize a variable value but we do not want to re-declare the variable name?
const keyword is not totally suitable for this case, that is why there was a need for the
let allows re-initialization but does not allow redeclaration
let supports changing the value of the container/variable
// declaration let saltContainer; // initialization saltContainer = "salt"; //re-initialization saltContainer = "BlackSalt" console.log(saltContainer) // output: BlackSalt
let does not allow re-declaring an existing variable name
// declaration let saltContainer; // re-declaration with initialization let saltContainer = "salt"; console.log(saltContainer) // output: Identifier 'saltContainer' has already been declared
Hurry and that is it about var, const, and let.
But wait, since I already know why these 3 exists, when should I use them?
My recommendations are:
- Always use
constif you are not planning to change the variable value.
letif you will be changing the value of the variable later.
- Don't use
- var is global and functional scope (article coming up on this)
- const and let are block or functional scope
Thanks for reading this far, I hope you have learned one or two things from this article?
If you find this helpful feel free to drop an 👍 on the article. It inspires me to continue improving and make more awesome content.
If you would like to connect with me then come and say hi @unclebay143 as I am always active in communicating with other developers on Twitter.