Advertisement
Google Ad Slot: content-top
JS Variables
In JavaScript, variables are used to store data values. They act as containers to hold values like numbers, strings, objects, etc.
Declaring Variables in JavaScript:
You can declare JavaScript variables using:
var(old way, avoid using in modern code)let(block-scoped, preferred for variable values that change)const(block-scoped, preferred for constants or values that won't change)
Variable Rules:
- Variable names must start with a letter,
_, or$. - Variable names are case-sensitive (
myVaris different fromMyVar). - Reserved JavaScript keywords cannot be used as variable names (
var,let,const).
Differences Between var, let, and const
Keyword |
Scope |
Can Reassign? |
Can Redeclare? |
Hoisting |
|---|---|---|---|---|
var |
Function Scope |
Yes |
Yes |
Hoisted with |
let |
Block Scope |
Yes |
No |
Hoisted without initialization |
const |
Block Scope |
No |
No |
Hoisted without initialization |
Variable Scope:
1. Global Scope:
- Variables declared outside any function or block are global.
- Accessible anywhere in the code.
2. Function Scope:
- Variables declared with
varinside a function are function-scoped.
3. Block Scope:
- Variables declared with
letandconstinside a block{}are block-scoped.
Variable Hoisting:
- Variables declared with
varare hoisted to the top of their scope and initialized withundefined. - Variables declared with
letandconstare hoisted but not initialized.
Best Practices for Variables:
- ✅ Use
constby default. - ✅ Use
letif the variable needs to change. - ❌ Avoid
varunless absolutely necessary. - ✅ Use meaningful variable names (
userAge,totalPrice). - ✅ Follow camelCase naming convention (
firstName,lastValue).
Data Types of Variables
JavaScript variables can store values of different data types:
- String:
"Hello" - Number:
42 - Boolean:
true/false - Null:
null - Undefined:
undefined - Object:
{ key: "value" } - Array:
[1, 2, 3] - Function:
function() {}
Constants in JavaScript (const)
- Must be initialized at declaration.
- Cannot be reassigned.
- Object and array values can still be modified (only the reference is constant).