Hey Guys! In this blog post I am going to explain in detail about javascript variables,
Javascript variables are containers that holding pieces of data.
There are three keywords used when declaring the variable in Javascript, namely,var
let
and.const
They follow this pattern or syntax.
1 |
var variableName = variableValue; |
Javascript variables are dynamic typing means
that they can change from one data type to another. Below, the variable technology change from string to number and then boolean.
1 2 3 |
var technology = 'javascript'; // javascript javascript = 100; // 100 javascript = false; // false |
Three ways of declaring variables
=> var
This was the only way to declare variable before ES6. Here you can declare the same variables more than one time and can be updated.
1 2 3 |
var technology = 'javascript'; var technology = 'jquery'; console.log(technology); |
If you declare variable inside the block statement, the variable will leak outside.
1 2 3 4 5 6 |
var bodyWeight = 50; if (bodyWeight > 49) { var water = 1.4; console.log(`For body weight of ${bodyWeight}kg, you should drink water atleast ${water}litre`); } console.log(water); // 1.4 |
=> let and const
let
and const
are the new ways for declaring variables introduced in ES6. In let
and const
you cannot declare the variable twice.
1 2 |
let technology = 'javascript'; let technology = 'jquery'; // Uncaught SyntaxError: Identifier 'jquery' has already been declared |
In most case let
and const
are almost same, the only difference I known, const
cannot be updated but let
can.
1 2 3 4 5 6 7 8 |
// let can be updated let technology = 'javascript'; technology = 'jquery'; console.log(technology); // jquery // const cannot be updated const othertechnology = 'node'; othertechnology = 'java'; // Uncaught TypeError: Assignment to constant variable. |
The variable is not leaked outside of the block statement if you use let
or const
.
1 2 3 4 5 6 |
const bodyWeight = 50; if (bodyWeight > 49) { const water = 1.4; console.log(`For body weight of ${bodyWeight}kg, you should drink water atleast ${water}litre`); } console.log(water); // Uncaught ReferenceError: water is not defined |
When to use var, let and const
Always use const
when declaring variable, use only let
when you want update the variable. var
shouldn’t be used in ES6 and above.
I hope you will find this blog useful. Please comments to make it even more better.
Recent Comments