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:-
var x = 10;
console.log(x); // will return 10
var x = 20;
console.log(x); // will return 20
x = 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.
let x = 10;
console.log(x); // will return 10
let x = 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.
const x = 10;
console.log(x); // will return 10
x = 10;
console.log(x); // will show an error
const x = 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'.
Top comments (0)