Variables and constants
In JavaScript, variables are used to store data values, and constants hold values that do not change. There are three ways to declare variables: var, let, and const.
1. Declaring Variables
JavaScript provides two modern ways (let and var) and one older way (var) to declare variables.
1.1 Using var (Old Way, Avoid Using)
- Can be redeclared within the same scope.
- Function-scoped (not block-scoped).
- May lead to unexpected behavior due to hoisting.
var name = "Alice";
console.log(name); // Output: Alice
var name = "Bob"; // Redeclaration is allowed
console.log(name); // Output: Bob
🔹 Why avoid var?
Since var does not respect block scope, it can cause unexpected issues in larger programs.
1.2 Using let (Modern & Recommended)
Block-scoped (only available inside {} where declared).
Can be updated but not redeclared in the same scope.
let age = 25;
console.log(age); // Output: 25
age = 30; // Allowed: Updating the variable
console.log(age); // Output: 30
// let age = 40; ❌ Error: Cannot redeclare the variable
🔹 Best practice: Use let for values that may change.
2. Declaring Constants (const)
- Block-scoped like let.
- Cannot be reassigned after initialization.
- Must be initialized when declared.
const PI = 3.14;
console.log(PI); // Output: 3.14
// PI = 3.14159; ❌ Error: Cannot reassign a constant
🔹 Best practice: Use const for values that should not change (e.g., mathematical constants, API keys).
Scope of Variables
JavaScript variables have different scopes depending on how they are declared:
Variable Type | Scope | Can be Updated? | Can be Redeclared? | Hoisted? |
---|---|---|---|---|
var | Function | ✅ Yes | ✅ Yes | ✅ Yes (with undefined ) |
let | Block | ✅ Yes | ❌ No | ❌ No |
const | Block | ❌ No | ❌ No | ❌ No |