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.
Top comments (4)
Immutable force? You even continue to describe it correctly. Maybe call it something else - but
const
is not immutable. It just cannot be re-assigned (that implies that re-declarations are not possible, too).Mutable:
Compare that with, e.g.,
Object.freeze
, which truly makes it immutable (ignores any modification attempts):If you are referring to the case of 'const' in Object and Arrays, in which the values can be modified. Then you are correct, const isn't an immutable force.
Was literally reading into this last night for my code. Thank you for the write up, it helped clear a few things up for me :)
I am Glad, it helps.