JavaScript Variables
What are Variables?
Variables in JavaScript are containers for storing data values. They allow us to store, update, and manipulate data in our programs.
1️⃣ Declaring Variables in JavaScript
JavaScript provides three ways to declare variables:
Keyword | Scope | Reassignment | Hoisting | Mutable |
---|---|---|---|---|
var | Function-scoped | ✅ Yes | ✅ Yes | ✅ Yes |
let | Block-scoped | ✅ Yes | ❌ No | ✅ Yes |
const | Block-scoped | ❌ No | ❌ No | ❌ No |
🔹 Using var
(Old Way, Avoid Using)
🚨 Problems with var
:
- Function-scoped (not block-scoped)
- Can be redeclared and overwritten, which can lead to bugs
- Gets hoisted (moved to the top of its scope), but initialized as
undefined
🔹 Using let
(Recommended)
✅ Better than var
because:
- Block-scoped (only accessible inside
{}
where it was declared) - Cannot be redeclared within the same scope
🔹 Using const
(Best for Constants)
✅ Use const
when:
- The value should not change
- You are working with constant values
📌 Note: If you declare an object or array with const
, you can modify its properties but cannot reassign it.
2️⃣ Variable Naming Rules
✅ Can contain letters, digits, _
, and $
✅ Must start with a letter, _
, or $
❌ Cannot start with a digit
❌ Cannot use reserved keywords like let
, var
, const
, function
, etc.
3️⃣ Hoisting in JavaScript
var
is hoisted but initialized asundefined
let
andconst
are hoisted but not initialized, causing a ReferenceError if accessed before declaration.
4️⃣ Dynamic Typing (No Need to Specify Type)
JavaScript is dynamically typed, meaning variables do not have a fixed type.
🎯 Summary
✅ Use let
for the variables that will change
✅ Use const
for constants that won’t change
✅ Avoid var
(due to scoping issues)
✅ JavaScript variables do not have fixed types
✅ Variables must be declared before use
🚀 Now you’re ready to use JavaScript variables like a pro! Let me know if you need more details. 😊