Back to: ReactJS Tutorials
JavaScript let and const Keywords:
In this article, we will discuss let and const keywords in JavaScript. These are two keywords we are going to use a lot in our upcoming articles, especially const.
JavaScript let and const Keywords:
In JavaScript, let and const are different ways of creating variables. We know var that creates a variable in JavaScript. Now the thing is some variables never change, they are so-called constants. They are all just variables because JavaScript only knows var. With ES6, a version of JavaScript, two different keywords were introduced, let and const. var still works but you’re highly encouraged to use let and const.
In simple words, let is the new var, you use it for variable values. Let and Const are all to changing something behind the scenes about the scope of variables. But the most important takeaway here is to use let if you want to create a variable that really varies (changing values). Use const if you plan on creating a constant value, so something which you only assign once and never changes.
In our upcoming articles, you will never see var, you will only see let and const, and mostly it’s const. So it shouldn’t confuse you, it’s simply the same as var, just in a more modern way, and in the case of const, although clearly showing, this is never going to receive a new value.
We have another JS editor that is JSBIN, an online Web Editor. You can access it from here https://jsbin.com/. When you open JSBIN, the window will look like the following,
By default, HTML and Output tabs are selected. To use it for JavaScript, just click on the JavaScript Console tab and disable HTML and Output by clicking on HTML and Output tab. Now the window will look like the following,
This Online Web Editor makes it easy for us to enter some JavaScript and see some console output. Now on the left-hand side, you can right next-generation JavaScript and on the right-hand side, you will see the output. Now, let’s see let and const.
Here, we have created a variable ‘myCar’ and assigned a string value to it. And after printing it on the console, we modified myCar to some other string value. Then again we are printing it on the console. So you can run this code by clicking on the “Run” button. And you can see the output. It prints “Alto” in 1st line and “Audi” in 2nd line. Now if we change var to let,
Nothing’s going to change. It still works in the same way. If you use const, Here, it throws an error, since we try to reassign a constant variable. This is const and this is the idea behind const. You can say this should never get a new value and if you accidentally write some code where you reassign it you get the error.
In the next article, I am going to discuss JavaScript Arrow Functions with Examples. Here, in this article, I try to explain let and const keywords in JavaScript. I hope you enjoy this let and const keywords in the JavaScript article.