Advertisement
← Back to Examples

JavaScript Examples

6 production-ready code snippets

Fetch API with Async/Await

Easy

Make HTTP requests with proper error handling

#fetch#async#error-handling
async function fetchData(url) {
  try {
    const response = await fetch(url);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Fetch failed:', error);
    throw error;
  }
}

// Usage
fetchData('https://api.example.com/data')
  .then(data => console.log(data))
  .catch(err => console.error(err));

Array Map, Filter, Reduce

Easy

Essential array methods for data transformation

#arrays#map#filter#reduce
const users = [
  { name: 'John', age: 25, active: true },
  { name: 'Jane', age: 30, active: false },
  { name: 'Bob', age: 35, active: true }
];

// Map - transform array
const names = users.map(user => user.name);
// ['John', 'Jane', 'Bob']

// Filter - get subset
const activeUsers = users.filter(user => user.active);
// [{ name: 'John', ... }, { name: 'Bob', ... }]

// Reduce - calculate total
const totalAge = users.reduce((sum, user) => sum + user.age, 0);
// 90

// Chaining methods
const activeUserNames = users
  .filter(user => user.active)
  .map(user => user.name);
// ['John', 'Bob']

Promise.all for Parallel Requests

Medium

Execute multiple async operations in parallel

#promises#async#parallel
async function fetchMultipleEndpoints() {
  try {
    const [users, posts, comments] = await Promise.all([
      fetch('https://api.example.com/users'),
      fetch('https://api.example.com/posts'),
      fetch('https://api.example.com/comments')
    ]);

    const usersData = await users.json();
    const postsData = await posts.json();
    const commentsData = await comments.json();

    return { usersData, postsData, commentsData };
  } catch (error) {
    console.error('One or more requests failed:', error);
    throw error;
  }
}

// Alternative: Promise.allSettled (doesn't fail if one fails)
async function fetchWithFallback() {
  const results = await Promise.allSettled([
    fetch('https://api.example.com/users'),
    fetch('https://api.example.com/posts')
  ]);

  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      console.log(`Request ${index} succeeded`, result.value);
    } else {
      console.log(`Request ${index} failed`, result.reason);
    }
  });
}

Debounce Function

Medium

Limit function execution rate for better performance

#performance#debounce#optimization
function debounce(func, delay) {
  let timeoutId;

  return function(...args) {
    // Clear previous timeout
    clearTimeout(timeoutId);

    // Set new timeout
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// Usage: Search input
const searchInput = document.querySelector('#search');

const handleSearch = debounce((event) => {
  console.log('Searching for:', event.target.value);
  // Make API call here
}, 500); // Wait 500ms after user stops typing

searchInput.addEventListener('input', handleSearch);

// Alternative: Throttle (run at most once per interval)
function throttle(func, interval) {
  let lastTime = 0;

  return function(...args) {
    const now = Date.now();

    if (now - lastTime >= interval) {
      lastTime = now;
      func.apply(this, args);
    }
  };
}

Deep Clone Object

Medium

Create a true copy of nested objects

#objects#clone#immutability
// Method 1: JSON parse/stringify (simple but limited)
function deepClone1(obj) {
  return JSON.parse(JSON.stringify(obj));
}

// Limitations: doesn't work with functions, dates, undefined

// Method 2: Recursive clone (handles more cases)
function deepClone2(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  if (obj instanceof Date) {
    return new Date(obj.getTime());
  }

  if (obj instanceof Array) {
    return obj.map(item => deepClone2(item));
  }

  if (obj instanceof Object) {
    const clonedObj = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone2(obj[key]);
      }
    }
    return clonedObj;
  }
}

// Method 3: Modern structuredClone (best, but new)
const original = { name: 'John', nested: { age: 30 } };
const copy = structuredClone(original);

// Test deep clone
copy.nested.age = 31;
console.log(original.nested.age); // 30 (unchanged)

Local Storage Helper

Easy

Safe wrapper for localStorage with JSON support

#storage#localStorage#helper
const storage = {
  // Set item with JSON serialization
  set(key, value) {
    try {
      const serialized = JSON.stringify(value);
      localStorage.setItem(key, serialized);
    } catch (error) {
      console.error('Error saving to localStorage:', error);
    }
  },

  // Get item with JSON parsing
  get(key, defaultValue = null) {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : defaultValue;
    } catch (error) {
      console.error('Error reading from localStorage:', error);
      return defaultValue;
    }
  },

  // Remove item
  remove(key) {
    try {
      localStorage.removeItem(key);
    } catch (error) {
      console.error('Error removing from localStorage:', error);
    }
  },

  // Clear all
  clear() {
    try {
      localStorage.clear();
    } catch (error) {
      console.error('Error clearing localStorage:', error);
    }
  }
};

// Usage
storage.set('user', { name: 'John', age: 30 });
const user = storage.get('user');
console.log(user.name); // 'John'
Advertisement