We can say that a variable works as a container that holds the value that we may use later on scripting our code. This way we can use those variables whenever we want and save it from repeating and defining it again every time we have to use it. That’d been frustrating othewise for programmers. Excet you declare a variable with ‘const’ it can change, while we add the const keyword we declare that it has to remain constant through out our code.
They are untyped by nature so that we can assign different values to them at various instances in the same code piece. That’s what makes them untyped and easy to use with a lot of functionality.
Variable ‘Keywords’ – const, let and var
THe variables are declared by using 3 keywords to distinguish which one is which here we are using const, let and var with examples.
The const keyword
We should understand again that once we declare variable with const keyword it cannot be changed. It also can only be used only when it is needed on the important occasions where we need to keep the value of variable unchanged. The best example would be using it while coding your smart contracts.
const name = "John"; // you will notice we changed to 'Andrew' it's bound to show an error TypeError: Assignment to the constant variable name = "Smith";
We will see a typeerror whenever we would try to assign a new value to a constant variable.
The let keyword
We need to understand that the let keyyword will declare and bind the variable name with the value assigned to it. Here is the example to demonstrate it further:
let name = "John"; // It binds the variable name "name" bind variable name "name" to thestring value "John" console.log(name); // John name = "Smith"; // Where would this be used? console.log(name); // Smith
In the example we have declared variable giving it “John” value and later “Smith”. Let’s see other example this time we have to add a comma “,” at the end of firstName
let firstName = "John", lastName = "Smith"; console.log(firstName); console.log(lastName);
On the other hand, if we don’t declare the variables with values the that would remain undefined. If we don’t add value at all it will remain so untile we add value to it. Next let’s see this example where we are not defining or adding value to age it will remain undefined until we add value to it.
let age; console.log(age); // undefined age = 25; console.log(age); // 25
The var keyword
It’s better to use “let” keyword to define variables instead of “var” which was fine until ES2015 upgrade after that using it produced bugs. More on that when we will define functions. See the example for var keyword which shows there’s not any difference betweem let and var keywords.
var firstName = "John", lastName = "Smith"; console.log(firstName); console.log(lastName);
After ES2015 programmers are bound to work with let instead of var which is highly recommended.