Variables & Scope
let, const, and var
Always default to `const`. Use `let` when reassignment is needed. Avoid `var` to prevent scope hoisting issues.
let score = 10;
score = 20; // Reassignment allowed
const apiKey = 'abc';
// apiKey = 'def'; // TypeError
// Block scope example
if (true) {
let x = 5;
const y = 10;
}
// console.log(x); // ReferenceErrorArrow Functions
Syntax & 'this' binding
Arrow functions provide a shorter syntax and lexically bind the `this` value.
// Traditional
function add(a, b) {
return a + b;
}
// Arrow Function (implicit return)
const add = (a, b) => a + b;
// Single parameter (parentheses optional)
const greet = name => `Hello ${name}`;
// Multi-line body
const calc = (x, y) => {
const result = x * y;
return result;
};Destructuring
Objects & Arrays
Easily extract properties into variables.
// Object Destructuring
const user = { name: 'Alice', age: 25, role: 'admin' };
const { name, age } = user;
// Renaming variables
const { role: userRole } = user;
// Array Destructuring
const colors = ['red', 'green', 'blue'];
const [primary, secondary] = colors;Spread & Rest Operators
The '...' syntax
Spread expands iterables into elements. Rest gathers remaining elements into an array.
// Spread (Copying / Merging)
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }
// Rest (Function Parameters)
function sum(...args) {
return args.reduce((a, b) => a + b, 0);
}Array Methods
map, filter, reduce
Functional approaches to transforming arrays.
const nums = [1, 2, 3, 4];
// map: transform elements
const doubled = nums.map(n => n * 2);
// filter: keep matching elements
const evens = nums.filter(n => n % 2 === 0);
// reduce: accumulate to a single value
const sum = nums.reduce((acc, curr) => acc + curr, 0);find, some, every
// find: returns first matching element
const firstEven = nums.find(n => n % 2 === 0);
// some: true if ANY match
const hasNegative = nums.some(n => n < 0);
// every: true if ALL match
const allPositive = nums.every(n => n > 0);Promises & Async/Await
Handling Asynchrony
Async/await makes asynchronous code look synchronous.
// Creating a Promise
const wait = (ms) => new Promise(res => setTimeout(res, ms));
// Using Async/Await
async function fetchUser() {
try {
await wait(1000);
const res = await fetch('/api/user');
if (!res.ok) throw new Error('Failed');
const data = await res.json();
return data;
} catch (error) {
console.error(error);
}
}Optional Chaining & Nullish Coalescing
Safe Navigation
Safely access deep properties and handle null/undefined fallbacks.
const user = { profile: { email: '[email protected]' } };
// Optional Chaining (?.)
// Prevents "Cannot read property of undefined" errors
const city = user.address?.city;
// Nullish Coalescing (??)
// Only falls back if left side is null or undefined
const count = 0;
const displayCount = count ?? 10; // returns 0, whereas || would return 10