JS Basics
JavaScript Variables
Understand var, let, and const — when to use each, scope differences, and modern best practices.
JavaScript Variables
There are 4 ways to declare a JavaScript variable:
var— old way, function-scoped, avoid in modern JSlet— block-scoped, can be reassignedconst— block-scoped, cannot be reassigned- (no keyword) — creates global variable, always avoid this
var vs let vs const
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Re-declare | Yes | No | No |
| Re-assign | Yes | Yes | No |
Modern Best Practices
- Use
constby default - Use
letwhen you need to reassign - Never use
var
Destructuring
Destructuring allows you to unpack values from arrays or properties from objects.
Example
javascript
// const - cannot be reassigned
const PI = 3.14159;
const name = "DevForge";
// PI = 3; // Error!
// let - can be reassigned
let score = 0;
score = 100; // OK
score++; // OK
// Destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest); // [3, 4, 5]
const { name: userName, age, role = "user" } = {
name: "Alice",
age: 28
};
console.log(userName); // Alice
console.log(role); // user (default)
// Template literals
const greeting = `Hello, ${userName}! You are ${age} years old.`;
console.log(greeting);
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6];
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 };Try it yourself — JAVASCRIPT