This content originally appeared on DEV Community and was authored by Sultan Akhter
Ah, JavaScript variables! If you’ve ever found yourself scratching your head over the differences between var, let, and const, you’re not alone. Understanding these three can feel like trying to navigate a maze. But fear not, dear coder! I am here to clarify the confusion.
Basic Concept : Assigning and Redeclaration of Variable
Let’s start with ‘Var’ – The Old Guard of JS
The variable associated with ‘var’ keyword can be reassign and redeclared.
‘Let’ – The Modern contender
The variable associated with ‘let’ can be reassign but cannot be redeclared.
‘Const’ – The Immutable Force
The variable associated with ‘const’ can neither be reassign not redeclared.
If you are a beginner and want to know about the bare minimum about variables, then this STOP is for you. Below we will discuss some advance concepts related to variables which will come in handy like Scoping and Hoisting .
Scoping – Accessibility of variables within specific parts of code.
Where ‘var’ has Function Scope but ‘let’ and ‘const’ are Block Scope. It means ‘var’ can be accessed throughout the function even in blocks (if,else etc..) And ‘let’ and ‘const’ can be accessed inside its own Block.
Hoisting – In simple words, it means using variables without declaring them is called Hoisting.
‘var’ declaration is hoisted and initialized as ‘undefined’, you can use the variable before its declartion but its value will be undefined.
‘let’ and ‘const’ declaration is hoisted but not initialized, you cannot use the variable before its declaration, attempting to do so will result in ‘reference error’.
Thankyou for reading, I am starting my journey of posting, related to Web Development. Do like and share to support me.
If you have any question regarding the topic or the info shared in the blog, please leave a comment.
This content originally appeared on DEV Community and was authored by Sultan Akhter