let Vs const VS var in JS
let Vs const Vs var in JS
1)var
Socpe
They can be functionally and globally scoped They can be reassigned and redeclared var declarations are globally scoped and they get added to the global object whenever they are declared outside the scope of any function
Example of scope
var a = 20
function helloLogger(){
var b = "Hello
console.log("Global variable is",a)
}
helloLogger()
console.log(b)
Output :
Gloabl variable is 20
Error
Explanation :
The scope of 'a' is global and can be accessed anywhere in the script while variable 'b' only exists within the scope of helloLogger() function and cannot be accessed outside
Example of Reassigning
var a = 20
console.log(a)
a = 30
console.log(a)
Output:
20
30
Example of Redeclaration
var a = 20
console.log(a)
var a = "Hello"
console.log(a)
Output:
20
Hello
2)let
Scope
let is blocked scope and cannot be assigned to the global object '{}' make up a block and any variables declared within a block using let are only valid within the block
Scope Example
let a = 20
if(true){
let a = 30
}
console.log(a)
Output:
20
Explanation :
'a' declared within the {} of the if statement is only valid within the {} of the if statement and has a separate block in the memory as compared to the 'a' declared in line number 1 Hence any changes made inside the if block don't affect the variable declared in line number 1
Reassigning and Redeclaring
let can be Reassigned but not Redeclared
let a = 10
a = 20 // this is allowed
let a = 30 // this will throw an error
2)const
Scope: Like let, const is blocked scope and cannot be assigned to the global object
const a = 20
if(true){
const a = 30
}
console.log(a)
Output:
20
Explanation :
Same as that of let
Reassigning and Redeclaring
const variables can neither be Reassigned nor Redeclared Like the name suggests, const variables are expected to hold constant values that cannot be changed
const a = 10
a = 20 // this will throw an error
const a = 30 // this will also throw an error
Hope this helps you in understanding the concept of difference methods of variable declarations in JS. Please let me know in case of any error in my explanation Looking forward to your feedback
Thanks