Optional Chaining
JavaScriptconst name = user?.profile?.name;
const length = users?.length ?? 0;Notes
Safely access deeply nested properties without throwing errors. Use nullish coalescing (??) for default values.
Array Destructuring
JavaScriptconst [first, second, ...rest] = array;
const [a, , c] = [1, 2, 3]; // Skip second elementNotes
Extract values from arrays into distinct variables. Use commas to skip elements.
Object Destructuring
JavaScriptconst { name, age, city = 'Unknown' } = user;
const { name: userName, age: userAge } = user; // RenameNotes
Extract properties from objects. Set default values and rename variables during destructuring.
Template Literals
JavaScriptconst message = `Hello, ${name}!`;
const multiline = `
Line 1
Line 2
Line 3
`;Notes
Use backticks for string interpolation and multiline strings. Supports expressions inside ${}.
Arrow Functions
JavaScriptconst add = (a, b) => a + b;
const square = x => x * x;
const greet = () => 'Hello!';
const processArray = arr => arr.map(x => x * 2);Notes
Shorter syntax for functions. Implicit return for single expressions. Lexical 'this' binding.
Spread Operator
JavaScriptconst newArray = [...oldArray, newItem];
const merged = [...array1, ...array2];
const newObj = { ...oldObj, newProp: 'value' };Notes
Expand arrays and objects. Useful for copying, merging, and adding elements without mutation.
Array Methods Chain
JavaScriptconst result = data
.filter(item => item.active)
.map(item => item.name)
.sort()
.slice(0, 10);Notes
Chain array methods for powerful data transformations. Each method returns a new array.
Async/Await
JavaScriptasync function fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}Notes
Modern way to handle asynchronous operations. Always use try-catch for error handling.
Promise.all
JavaScriptconst [users, posts, comments] = await Promise.all([
fetchUsers(),
fetchPosts(),
fetchComments()
]);
// Handle partial failures
const results = await Promise.allSettled([...promises]);Notes
Execute multiple async operations in parallel. Use Promise.allSettled() to handle partial failures.
Debounce Function
JavaScriptfunction debounce(func, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
const debouncedSearch = debounce(search, 300);Notes
Limit function execution frequency. Useful for search inputs, resize handlers, and API calls.
Local Storage Helper
JavaScriptconst storage = {
set: (key, value) => localStorage.setItem(key, JSON.stringify(value)),
get: (key) => {
try {
return JSON.parse(localStorage.getItem(key));
} catch {
return null;
}
},
remove: (key) => localStorage.removeItem(key)
};Notes
Safe localStorage wrapper with JSON serialization and error handling.
Deep Clone Object
JavaScript// Simple deep clone
const clone = JSON.parse(JSON.stringify(obj));
// Better deep clone (handles functions, dates, etc.)
const deepClone = (obj) => {
if (obj === null || typeof obj !== 'object') return obj;
if (obj instanceof Date) return new Date(obj);
if (Array.isArray(obj)) return obj.map(deepClone);
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [key, deepClone(value)])
);
};Notes
JSON method is simple but limited. Custom function handles more data types properly.
Event Delegation
JavaScriptdocument.addEventListener('click', (e) => {
if (e.target.matches('.button')) {
handleButtonClick(e.target);
}
if (e.target.matches('.link')) {
handleLinkClick(e.target);
}
});Notes
Handle events for multiple elements with a single listener. Great for dynamic content.
Intersection Observer
JavaScriptconst observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
observer.unobserve(entry.target);
}
});
});
document.querySelectorAll('.animate-on-scroll')
.forEach(el => observer.observe(el));Notes
Efficiently detect when elements enter the viewport. Perfect for lazy loading and scroll animations.
Fetch with Timeout
JavaScriptasync function fetchWithTimeout(url, options = {}, timeout = 5000) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
...options,
signal: controller.signal
});
clearTimeout(timeoutId);
return response;
} catch (error) {
clearTimeout(timeoutId);
throw error;
}
}Notes
Add timeout functionality to fetch requests using AbortController.
Retry Function
JavaScriptasync function retry(fn, maxAttempts = 3, delay = 1000) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxAttempts) throw error;
await new Promise(resolve => setTimeout(resolve, delay * attempt));
}
}
}Notes
Retry failed async operations with exponential backoff. Useful for network requests.
Throttle Function
JavaScriptfunction throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
const throttledScroll = throttle(handleScroll, 100);Notes
Limit function execution to once per time period. Different from debounce - executes immediately.
URL Parameters
JavaScript// Get URL parameters
const params = new URLSearchParams(window.location.search);
const userId = params.get('userId');
// Set URL parameters
const url = new URL(window.location);
url.searchParams.set('page', '2');
window.history.pushState({}, '', url);Notes
Modern way to work with URL parameters. URLSearchParams provides a clean API.
Form Data Handling
JavaScript// Get form data as object
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
// Validate and submit
const isValid = Object.values(data).every(value => value.trim());
if (isValid) {
await submitForm(data);
}Notes
Extract form data efficiently. FormData works with all input types including files.
Custom Event System
JavaScriptclass EventEmitter {
constructor() {
this.events = {};
}
on(event, callback) {
if (!this.events[event]) this.events[event] = [];
this.events[event].push(callback);
}
emit(event, data) {
if (this.events[event]) {
this.events[event].forEach(callback => callback(data));
}
}
off(event, callback) {
if (this.events[event]) {
this.events[event] = this.events[event].filter(cb => cb !== callback);
}
}
}Notes
Simple event emitter pattern for decoupled communication between components.
