← Blog/JavaScript

50 JavaScript Snippets Every Beginner Should Know — Ready to Copy and Use

50 practical JavaScript snippets across 5 categories: DOM manipulation, arrays & strings, functions & logic, dates & numbers, and browser & storage. Every snippet tested and explained.

📅 2026-06-262 min read📚 Ebook #09

Why Snippets Matter

The fastest way to learn JavaScript is to see patterns in real code. Snippets are reusable building blocks — once you have them, you stop searching Stack Overflow for the same things repeatedly.

Here are 10 of the 50 snippets from the full collection.

DOM Manipulation

Select multiple elements and loop through them:

const items = document.querySelectorAll('.item');
items.forEach(item => item.classList.add('active'));

Toggle a CSS class:

const btn = document.querySelector('.btn');
btn.classList.toggle('active');

Arrays

Remove duplicates from an array:

const unique = [...new Set([1, 2, 2, 3, 4, 4, 5])];
// [1, 2, 3, 4, 5]

Find the first match in an array of objects:

const user = users.find(u => u.id === 42);

Functions & Logic

Debounce — delay a function until typing stops:

const debounce = (fn, delay) => {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
};

Deep clone an object:

const clone = structuredClone(original);

Dates & Numbers

Format a number as currency:

const formatCurrency = (amount) =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);

Time ago — "3 minutes ago":

const timeAgo = (date) => {
  const seconds = Math.floor((Date.now() - new Date(date)) / 1000);
  if (seconds < 60) return 'just now';
  if (seconds < 3600) return `${Math.floor(seconds/60)} minutes ago`;
  return `${Math.floor(seconds/3600)} hours ago`;
};

Browser & Storage

Copy text to clipboard:

await navigator.clipboard.writeText('Hello, World!');

Read URL parameters:

const getParam = (name) =>
  new URLSearchParams(window.location.search).get(name);

This is a preview. The full ebook includes all 50 snippets with complete code and explanations — covering debounce, throttle, memoize, UUID generation, cookie handling, offline detection, and much more.

Ready to Build This Yourself?

This article is a preview. The full ebook has complete code, detailed explanations, troubleshooting tips, and bonus sections — all in a downloadable PDF.

Buy Full Ebook — $1.50 in $YFIN
Pay with $YFIN on BNB Smart Chain · 30% burned permanently