
Difference between 'var', 'const' and 'let'
By reading this post, you will stop searching about this topic on google. So let's get started.
var
Before 2015 we had only one keyword to declare variables in javascript that was 'var'. The variable which will be assigned with 'var' keyword can me editable/ replaceable. Which is pretty risky cause you would not want to replace the value of the variable 'x'. So if you accidently replace it, it's not gonna show any error like " is not decaled ". Here is a small example below:-
varx=10;console.log(x);// will return 10varx=20;console.log(x);// will return 20x=30;console.log(x);// will return 30
let
After 2015 ECMA script introduced us 2 new keyword to declare variables. They were 'let' and 'const'. Now we will know about the javascript let keyword.
'let' is nice way to declare variables. Cause now we are using ECMAscript/ the modern javascript. The variable assigned with let is unchageable and also changeable. Let me show you an example.
letx=10;console.log(x);// will return 10letx=20;console.log(x);// will show an error like x is already been declared.x=20;console.log(x);// will return 20
So that's how you can change/ replace the value of x by just not including the keyword let. But if you include it, it will show an error.
const
The variable declared with 'const' is unchangeable. You can't replace or change the value of a constant variable. If you try to do that, it will show an error. Like " has already been declared.
constx=10;console.log(x);// will return 10x=10;console.log(x);// will show an errorconstx=20;console.log(x);// will show an error
So that was the difference between 'var', 'let' and 'const'. So which one should you use? I recommend you to use 'let'. It will be much effective than using 'var'.
Thanks for reading that post. Hope you have got your whole informations regarding that topic. And make sure you follow me to recieve all the informational post just like that.
:)
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse