JavaScript Variable: var, let & const

Hey everyone...

As we all know that we can declare variables in javaScript using var, let and const

keywords. So let's talk about all three of them one by one and understand how the work.

var : It is oldest way of variable declaration in JS. The scope of var is global and functional, that means if you have declared a var inside function you cannot access it's value outside of it whereas if you have declare it outside a function than you can access it globally. A var once declared can always be redeclared and reassigned any value. Also if you use var variable before the declaration, it initializes with the undefined value. Example:

<script>
var x = 20;
console.log(x);
function varExample(){
var x = 15;
console.log(x);
}
var x = 10;
var x = 18;
console.log(x);
</script>

Output:

20
10
18

let : let is the most used way of variable declaration in JavaScript. The scope of let keyword is block ({block..}), which means if you have declared it inside a block and try to access it outside of the block you will get an error. It cannot be redeclared but it can be reassigned new value. Also if you try to use it before declaration it does not initializes with undefined and you'll get an error. Example

<script>
let a = 20;
console.log(a);
{

let b = 30;
console.log(b);
}
console.log(a);
</script>

Output:

20
30
20

const : const key word has every property of let keyword except that user cannot update it's value. The user is require to initialize value to a const variable at the time of declaration or else it returns an error. Also one interesting this about const is, though the user cannot change the properties of const object but can definitely change the values of properties of const object. Example:

<script>
const obj = {
a : 10,
x : "I am a number"
}
// this is allowed
obj.a = 20;
// this is not allowed
obj = {
b : 20,
x: "I am a number"
}
</script>

Output:

Uncaught SyntaxError: Unexpected identifier

So that was all about var, let and const in Javascript. Hope so it added some value to your learnings and you got to know something extra reading it.
Have a Good Day ahead!

Happy Learning ◡‿◡