In JavaScript, variables are used to store and manage data. They act as containers for values that can be accessed and manipulated throughout your program.
Three Ways to Declare Variables
JavaScript provides three ways to declare variables:
-
var
→ The older way, has function-scoped behavior. -
const
→ Block-scoped, cannot be reassigned after declaration. -
let
→ Block-scoped, allows reassignment but prevents redeclaration.
Understanding their differences is crucial for writing efficient and bug-free JavaScript code. Let's dive in!
🔴 Using var
(Function-Scoped)
The var
keyword was the original way to declare variables in JavaScript. However, it has some quirks due to function scoping and hoisting.
Example: Function Scope of var
var number = 10;
function showNumber() {
console.log(number); // ✅ Accessible inside the function
}
showNumber();
console.log(number); // ✅ Also accessible outside
Output:
10
10
Key Notes:
-
var
is function-scoped, meaning it is accessible throughout the function. - Variables declared with
var
can be redeclared, leading to potential bugs. - It gets hoisted to the top of its scope, sometimes causing unexpected behavior.
Use var
only if you must support older JavaScript versions.
🔵 Using const
(Immutable Variables)
The const keyword, introduced in ES6, is block-scoped and ensures that the variable cannot be reassigned after initialization.
Example: Constant Variables with const
const PI = 3.1416;
console.log(PI); // ✅ Works fine
PI = 3.14; // ❌ TypeError: Assignment to constant variable
Output:
3.1416
TypeError: Assignment to constant variable
Key Notes:
- It ensures data integrity by preventing accidental modifications.
- It makes your code more predictable and easier to debug.
- Helps in writing safer and more readable JavaScript.
Use const
by default, unless you know the value will change.
🟢 Using let
(Block-Scoped & Reassignable)
The let
keyword is an improved version of var
, allowing block-scoped variables that can be reassigned but not redeclared.
Example: Block Scope of let
function testLet() {
let number = 10;
console.log(number); // ✅ Accessible within the function
}
testLet();
console.log(number); // ❌ ReferenceError: number is not defined
Output:
10
ReferenceError: number is not defined
Key Notes:
- It prevents variable redeclaration, reducing accidental modifications.
- It has block scope, making it more predictable than
var
. - It does not get hoisted in an unpredictable way like
var
.
Use let
when you need a variable that can be reassigned but should remain within a limited scope.
Conclusion
- Use const for values that shouldn’t change.
- Use let for reassignable values.
- Avoid var unless working with older JavaScript code.
To write better code in JavaScript, we need to understand these differences and MASTER them.
That's it for today!
Happy Coding! 🤩