DevSheet

Developer Cheat Sheet Reference

Optional Chaining

JavaScript
const name = user?.profile?.name;
const length = users?.length ?? 0;
#es2020#optional chaining#safety

Notes

Safely access deeply nested properties without throwing errors. Use nullish coalescing (??) for default values.

Array Destructuring

JavaScript
const [first, second, ...rest] = array;
const [a, , c] = [1, 2, 3]; // Skip second element
#es6#destructuring#arrays

Notes

Extract values from arrays into distinct variables. Use commas to skip elements.

Object Destructuring

JavaScript
const { name, age, city = 'Unknown' } = user;
const { name: userName, age: userAge } = user; // Rename
#es6#destructuring#objects

Notes

Extract properties from objects. Set default values and rename variables during destructuring.

Template Literals

JavaScript
const message = `Hello, ${name}!`;
const multiline = `
  Line 1
  Line 2
  Line 3
`;
#es6#strings#interpolation

Notes

Use backticks for string interpolation and multiline strings. Supports expressions inside ${}.

Arrow Functions

JavaScript
const add = (a, b) => a + b;
const square = x => x * x;
const greet = () => 'Hello!';
const processArray = arr => arr.map(x => x * 2);
#es6#functions#arrow

Notes

Shorter syntax for functions. Implicit return for single expressions. Lexical 'this' binding.

Spread Operator

JavaScript
const newArray = [...oldArray, newItem];
const merged = [...array1, ...array2];
const newObj = { ...oldObj, newProp: 'value' };
#es6#spread#arrays#objects

Notes

Expand arrays and objects. Useful for copying, merging, and adding elements without mutation.

Array Methods Chain

JavaScript
const result = data
  .filter(item => item.active)
  .map(item => item.name)
  .sort()
  .slice(0, 10);
#arrays#functional#chaining

Notes

Chain array methods for powerful data transformations. Each method returns a new array.

Async/Await

JavaScript
async function fetchData() {
  try {
    const response = await fetch('/api/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
  }
}
#async#promises#error handling

Notes

Modern way to handle asynchronous operations. Always use try-catch for error handling.

Promise.all

JavaScript
const [users, posts, comments] = await Promise.all([
  fetchUsers(),
  fetchPosts(),
  fetchComments()
]);

// Handle partial failures
const results = await Promise.allSettled([...promises]);
#promises#async#parallel

Notes

Execute multiple async operations in parallel. Use Promise.allSettled() to handle partial failures.

Debounce Function

JavaScript
function debounce(func, delay) {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
}

const debouncedSearch = debounce(search, 300);
#performance#optimization#utility

Notes

Limit function execution frequency. Useful for search inputs, resize handlers, and API calls.

Local Storage Helper

JavaScript
const 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)
};
#storage#utility#browser

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)])
  );
};
#objects#utility#cloning

Notes

JSON method is simple but limited. Custom function handles more data types properly.

Event Delegation

JavaScript
document.addEventListener('click', (e) => {
  if (e.target.matches('.button')) {
    handleButtonClick(e.target);
  }
  if (e.target.matches('.link')) {
    handleLinkClick(e.target);
  }
});
#events#dom#performance

Notes

Handle events for multiple elements with a single listener. Great for dynamic content.

Intersection Observer

JavaScript
const 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));
#performance#scroll#animation

Notes

Efficiently detect when elements enter the viewport. Perfect for lazy loading and scroll animations.

Fetch with Timeout

JavaScript
async 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;
  }
}
#fetch#timeout#abort

Notes

Add timeout functionality to fetch requests using AbortController.

Retry Function

JavaScript
async 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));
    }
  }
}
#async#error handling#utility

Notes

Retry failed async operations with exponential backoff. Useful for network requests.

Throttle Function

JavaScript
function 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);
#performance#optimization#utility

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);
#url#browser#navigation

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);
}
#forms#validation#dom

Notes

Extract form data efficiently. FormData works with all input types including files.

Custom Event System

JavaScript
class 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);
    }
  }
}
#events#patterns#class

Notes

Simple event emitter pattern for decoupled communication between components.

Bolt.new logo