Confused by var, let, and const? Let's Clear the Mess

Sultan Akhter - Jul 16 - - Dev Community

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.
Image description

'Let' - The Modern contender

The variable associated with 'let' can be reassign but cannot be redeclared.
Image description

'Const' - The Immutable Force

The variable associated with 'const' can neither be reassign not redeclared.

Image description

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.

Image description

Hoisting - In simple words, it means using variables without declaring them is called Hoisting.

Image description

'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.

. . .
Terabox Video Player