Toolkit
Hire me
JavaScript

JavaScript Snippets - 70 Ready-made

JavaScript Snippets - 70 Ready-made in Jwala Baheliya's frontend toolkit. A live javascript utility with copy-ready output and in-browser previews.

Visual Guide
A cleaner, more guided way to use JavaScript Snippets - 70 Ready-made.

The left rail keeps navigation nearby, the right rail keeps your reading position visible, and the live tool stays front and center once you are ready to use it.

Category
JavaScript
Mode
Interactive docs
Route
/js-gallery
What It Does
JavaScript Snippets - 70 Ready-made is useful when you need frontend logic, data conversion, or browser-side code output that you can test and reuse quickly.
How To Use
Paste code, JSON, markup, or the input the tool needs. Then adjust the options and watch the output update live.
What You Get
Copy-ready frontend code, transformed data, or browser-friendly output.

What This Tool Does

JavaScript Snippets - 70 Ready-made is useful when you need frontend logic, data conversion, or browser-side code output that you can test and reuse quickly.

If you are not sure where to start, use the live controls below, watch the preview change, and copy the result only when it matches what you want in your project.

Live Tool

Interactive, client-side, and still running directly inside this docs page.

All tools
Every snippet includes vanilla HTML, CSS, and ES6 JavaScript.
70
Smooth Scroll to Section

Native smooth scrolling to any element.

…scroll spacer…
🎯 target section
const scrollButton = document.querySelector(".scroll-btn");
const pricingSection = document.querySelector("#pricing");

scrollButton?.addEventListener("click", () => {
  pricingSection?.scrollIntoView({
    behavior: "smooth",
    block: "start",
  });
});
Scroll To Top Button

Show a button after scrolling, then jump to top.

const toTopButton = document.querySelector("#toTop");

window.addEventListener("scroll", () => {
  const shouldShow = window.scrollY > 300;
  toTopButton?.classList.toggle("is-visible", shouldShow);
});

toTopButton?.addEventListener("click", () => {
  window.scrollTo({ top: 0, behavior: "smooth" });
});
Sticky Navbar

CSS position:sticky keeps nav pinned during scroll.

sticky navbar

scroll content line 1

scroll content line 2

scroll content line 3

scroll content line 4

scroll content line 5

scroll content line 6

scroll content line 7

scroll content line 8

const stickyNav = document.querySelector(".site-nav");
console.log("Sticky nav ready:", Boolean(stickyNav));
Active Navigation Highlight

Toggle an active class based on current section.

const navLinks = document.querySelectorAll(".section-nav a");

navLinks.forEach((link) => {
  link.addEventListener("click", () => {
    navLinks.forEach((item) => item.classList.remove("is-active"));
    link.classList.add("is-active");
  });
});
Scroll Progress Bar

Reflect page scroll % as a horizontal bar.

0%
const progressBar = document.querySelector("#progressBar");

window.addEventListener("scroll", () => {
  const scrollable = document.documentElement.scrollHeight - window.innerHeight;
  const progress = scrollable > 0 ? (window.scrollY / scrollable) * 100 : 0;
  if (progressBar) progressBar.style.width = progress + "%";
});
Intersection Observer Animation

Animate elements when they enter the viewport.

waiting…
const cards = document.querySelectorAll(".reveal-card");

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) entry.target.classList.add("in-view");
  });
}, { threshold: 0.4 });

cards.forEach((card) => observer.observe(card));
Lazy Image Loader

Native browser lazy loading — no JS needed.

lazy
const lazyImage = document.querySelector(".lazy-image");

lazyImage?.addEventListener("load", () => {
  lazyImage.classList.add("is-loaded");
});
Infinite Scroll

Load more items when a sentinel enters view.

  • item #1
  • item #2
  • item #3
  • item #4
  • item #5
  • item #6
  • item #7
  • item #8
loading more…
const feed = document.querySelector("#feed");
const sentinel = document.querySelector("#sentinel");
let page = 0;

const renderBatch = () => {
  const items = Array.from({ length: 6 }, (_, index) => page * 6 + index + 1);
  items.forEach((item) => {
    const li = document.createElement("li");
    li.className = "feed-item";
    li.textContent = "Loaded item #" + item;
    feed?.appendChild(li);
  });
  page += 1;
};

renderBatch();

const observer = new IntersectionObserver(([entry]) => {
  if (entry.isIntersecting) renderBatch();
});

if (sentinel) observer.observe(sentinel);
Dark / Light Theme Toggle

Toggle a `dark` class on <html>.

Currently: light

const themeToggle = document.querySelector("#themeToggle");

themeToggle?.addEventListener("click", () => {
  document.documentElement.classList.toggle("dark");
});
LocalStorage Theme Saver

Persist user's theme choice across reloads.

localStorage → light
const savedThemeKey = "theme";
const savedThemeToggle = document.querySelector("#savedThemeToggle");

const applyTheme = (theme) => {
  document.documentElement.classList.toggle("dark", theme === "dark");
};

const initialTheme = localStorage.getItem(savedThemeKey) || "light";
applyTheme(initialTheme);

savedThemeToggle?.addEventListener("click", () => {
  const nextTheme = document.documentElement.classList.contains("dark") ? "light" : "dark";
  applyTheme(nextTheme);
  localStorage.setItem(savedThemeKey, nextTheme);
});
Modal Popup

Open/close modal with backdrop click support.

const modal = document.querySelector("#modal");
const openModal = document.querySelector("#openModal");
const closeModal = document.querySelector("#closeModal");

openModal?.addEventListener("click", () => modal?.showModal());
closeModal?.addEventListener("click", () => modal?.close());

modal?.addEventListener("click", (event) => {
  if (event.target === modal) modal.close();
});
Toast Notification

Show a brief message with auto-dismiss.

const showToast = document.querySelector("#showToast");
const toastHost = document.querySelector("#toastHost");

showToast?.addEventListener("click", () => {
  const toast = document.createElement("div");
  toast.className = "toast";
  toast.textContent = "Saved successfully";
  toastHost?.appendChild(toast);
  setTimeout(() => toast.remove(), 2400);
});
Accordion

Toggle expandable panels, one open at a time.

The language of the web.
const accordionButtons = document.querySelectorAll(".accordion-trigger");

accordionButtons.forEach((button) => {
  button.addEventListener("click", () => {
    const panel = button.nextElementSibling;
    document.querySelectorAll(".accordion-panel").forEach((item) => item.classList.remove("is-open"));
    panel?.classList.toggle("is-open");
  });
});
Tabs

Switch content panels via tab buttons.

Content for Profile
const tabButtons = document.querySelectorAll(".tab-btn");
const tabPanels = document.querySelectorAll(".tab-panel");

tabButtons.forEach((button) => {
  button.addEventListener("click", () => {
    const { tab } = button.dataset;
    tabButtons.forEach((item) => item.classList.remove("is-active"));
    tabPanels.forEach((panel) => panel.classList.remove("is-active"));
    button.classList.add("is-active");
    document.querySelector('[data-panel="' + tab + '"]')?.classList.add("is-active");
  });
});
Dropdown Menu

Toggle a menu, close on outside click.

const menuButton = document.querySelector("#menuButton");
const menuList = document.querySelector("#menuList");

menuButton?.addEventListener("click", (event) => {
  event.stopPropagation();
  menuList?.classList.toggle("is-open");
});

document.addEventListener("click", (event) => {
  if (!menuList?.contains(event.target)) menuList?.classList.remove("is-open");
});
Offcanvas Sidebar

Slide-in sidebar with dim backdrop.

const sidebar = document.querySelector("#sidebar");
const sidebarBackdrop = document.querySelector("#sidebarBackdrop");
const openSidebar = document.querySelector("#openSidebar");
const closeSidebar = document.querySelector("#closeSidebar");

const toggleSidebar = (isOpen) => {
  sidebar?.classList.toggle("is-open", isOpen);
  sidebarBackdrop?.classList.toggle("is-open", isOpen);
};

openSidebar?.addEventListener("click", () => toggleSidebar(true));
closeSidebar?.addEventListener("click", () => toggleSidebar(false));
sidebarBackdrop?.addEventListener("click", () => toggleSidebar(false));
Mobile Hamburger Menu

Show/hide nav on small screens.

const hamburger = document.querySelector("#hamburger");
const mobileNav = document.querySelector("#mobileNav");

hamburger?.addEventListener("click", () => {
  const isOpen = mobileNav?.classList.toggle("is-open");
  hamburger.setAttribute("aria-expanded", String(Boolean(isOpen)));
});
Image Slider

Manual slider with dot indicators.

slide
const sliderImage = document.querySelector("#sliderImage");
const sliderImages = [
  "https://picsum.photos/id/1015/700/420",
  "https://picsum.photos/id/1016/700/420",
  "https://picsum.photos/id/1025/700/420",
];

document.querySelectorAll("[data-index]").forEach((button) => {
  button.addEventListener("click", () => {
    const index = Number(button.dataset.index);
    if (sliderImage) sliderImage.src = sliderImages[index];
  });
});
Auto Carousel

Auto-advance items on an interval.

Rustomjee
const brandCarousel = document.querySelector("#brandCarousel");
const brands = ["Rustomjee", "Godrej", "Kotak", "Tata", "Yes Bank"];
let brandIndex = 0;

setInterval(() => {
  brandIndex = (brandIndex + 1) % brands.length;
  if (brandCarousel) brandCarousel.textContent = brands[brandIndex];
}, 1500);
Counter Animation

Animate a number to a target on click.

0+
const startCounter = document.querySelector("#startCounter");
const counterValue = document.querySelector("#counterValue");

startCounter?.addEventListener("click", () => {
  let value = 0;
  const intervalId = setInterval(() => {
    value += 5;
    if (counterValue) counterValue.textContent = String(value);
    if (value >= 500) clearInterval(intervalId);
  }, 15);
});
Number Count Up

Smooth easing with requestAnimationFrame.

0
const countUpValue = document.querySelector("#countUpValue");
const countUpTarget = 8752;
const countUpDuration = 1500;

const countUp = () => {
  const start = performance.now();

  const step = (time) => {
    const progress = Math.min(1, (time - start) / countUpDuration);
    const value = Math.round(progress * countUpTarget);
    if (countUpValue) countUpValue.textContent = value.toLocaleString();
    if (progress < 1) requestAnimationFrame(step);
  };

  requestAnimationFrame(step);
};

countUp();
Typing Effect

Reveal text one character at a time.

▌
const typingText = document.querySelector("#typingText");
const typingSource = "console.log(\"hello world\");";
let typingIndex = 0;

setInterval(() => {
  typingIndex = typingIndex < typingSource.length ? typingIndex + 1 : 0;
  if (typingText) typingText.textContent = typingSource.slice(0, typingIndex);
}, 80);
Text Scramble Effect

Randomize characters, then settle on target.

Frontend Developer
const scrambleOutput = document.querySelector("#scrambleOutput");
const scrambleButton = document.querySelector("#scrambleButton");
const scrambleTarget = "Frontend Developer";
const scrambleChars = "!<>-_\\/[]{}=*?#";

const runScramble = () => {
  let frame = 0;
  const revealFrames = scrambleTarget.split("").map(() => Math.floor(Math.random() * 18) + 8);

  const update = () => {
    let nextValue = "";
    let complete = 0;

    scrambleTarget.split("").forEach((char, index) => {
      if (frame >= revealFrames[index]) {
        nextValue += char;
        complete += 1;
      } else {
        nextValue += scrambleChars[Math.floor(Math.random() * scrambleChars.length)];
      }
    });

    if (scrambleOutput) scrambleOutput.textContent = nextValue;
    if (complete < scrambleTarget.length) {
      frame += 1;
      requestAnimationFrame(update);
    }
  };

  update();
};

scrambleButton?.addEventListener("click", runScramble);
Read More Toggle

Expand/collapse long text blocks.

Frontend developer with 8+ years of experience crafting premium interfaces for g…
const readMoreText = document.querySelector("#readMoreText");
const readMoreButton = document.querySelector("#readMoreButton");
const shortText = "Frontend developer with 8+ years of experience crafting production-ready interfaces for large brands.";
const longText = shortText + " Strong in performance, accessibility, design systems, and smooth interactions.";
let isExpanded = false;

readMoreButton?.addEventListener("click", () => {
  isExpanded = !isExpanded;
  if (readMoreText) readMoreText.textContent = isExpanded ? longText : shortText;
  if (readMoreButton) readMoreButton.textContent = isExpanded ? "Read less" : "Read more";
});
Clipboard Copy

Async Clipboard API — modern & secure.

const copyEmail = document.querySelector("#copyEmail");
const email = "hello@example.com";

copyEmail?.addEventListener("click", async () => {
  await navigator.clipboard.writeText(email);
  copyEmail.textContent = "Copied";
});
Password Visibility Toggle

Swap input type between password and text.

const passwordInput = document.querySelector("#passwordInput");
const togglePassword = document.querySelector("#togglePassword");

togglePassword?.addEventListener("click", () => {
  const isHidden = passwordInput?.getAttribute("type") === "password";
  passwordInput?.setAttribute("type", isHidden ? "text" : "password");
  togglePassword.textContent = isHidden ? "Hide" : "Show";
});
Password Strength Meter

Score password against length + variety rules.

Too weak
const strengthPassword = document.querySelector("#strengthPassword");
const strengthLabel = document.querySelector("#strengthLabel");

const getStrength = (value) => {
  let score = 0;
  if (value.length >= 8) score += 1;
  if (/[A-Z]/.test(value)) score += 1;
  if (/\d/.test(value)) score += 1;
  if (/[^A-Za-z0-9]/.test(value)) score += 1;
  return score;
};

const labels = ["Too weak", "Weak", "Okay", "Good", "Strong"];

strengthPassword?.addEventListener("input", () => {
  const score = getStrength(strengthPassword.value);
  if (strengthLabel) strengthLabel.textContent = labels[score];
});
Form Validation

Regex-based email validator with live feedback.

enter an email
const emailForm = document.querySelector("#emailForm");
const emailInput = document.querySelector("#emailInput");
const emailFeedback = document.querySelector("#emailFeedback");
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

emailForm?.addEventListener("submit", (event) => {
  event.preventDefault();
  const isValid = emailPattern.test(emailInput?.value || "");
  if (emailFeedback) {
    emailFeedback.textContent = isValid ? "Valid email address" : "Please enter a valid email";
  }
});
Debounce Function

Delay a function until N ms after the last call.

debounced:
const debounce = (callback, wait = 300) => {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => callback(...args), wait);
  };
};

const debounceInput = document.querySelector("#debounceInput");
const debounceOutput = document.querySelector("#debounceOutput");

const updateOutput = debounce((value) => {
  if (debounceOutput) debounceOutput.textContent = "Debounced: " + value;
}, 400);

debounceInput?.addEventListener("input", (event) => {
  updateOutput(event.target.value);
});
Throttle Function

Run a function at most once every N ms.

counted: 0
const throttle = (callback, wait = 500) => {
  let lastRun = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastRun >= wait) {
      lastRun = now;
      callback(...args);
    }
  };
};

const throttleButton = document.querySelector("#throttleButton");
const throttleCount = document.querySelector("#throttleCount");
let clicks = 0;

const countClick = throttle(() => {
  clicks += 1;
  if (throttleCount) throttleCount.textContent = String(clicks);
}, 500);

throttleButton?.addEventListener("click", countClick);
Fetch API Example

GET JSON from an API with async/await.

—
const fetchStars = document.querySelector("#fetchStars");
const fetchResult = document.querySelector("#fetchResult");

fetchStars?.addEventListener("click", async () => {
  if (fetchResult) fetchResult.textContent = "Loading...";

  try {
    const response = await fetch("https://api.github.com/repos/facebook/react");
    const data = await response.json();
    if (fetchResult) fetchResult.textContent = "Stars: " + data.stargazers_count.toLocaleString();
  } catch (error) {
    if (fetchResult) fetchResult.textContent = "Request failed";
  }
});
Search Filter

Client-side filter with .filter() + includes().

  • Rustomjee
  • Godrej
  • Kotak
  • Tata
  • Yes Bank
  • AU Bank
  • VIP Bags
  • Kokuyo Camlin
const filterInput = document.querySelector("#filterInput");
const filterItems = [...document.querySelectorAll("#filterList li")];

filterInput?.addEventListener("input", () => {
  const query = filterInput.value.toLowerCase();
  filterItems.forEach((item) => {
    const visible = item.textContent.toLowerCase().includes(query);
    item.hidden = !visible;
  });
});
Live Search

Debounced search that queries as you type.

const liveSearchInput = document.querySelector("#liveSearchInput");
const liveSearchResults = document.querySelector("#liveSearchResults");
let liveSearchTimeout;

const mockSearch = (query) => [query + " result A", query + " result B", query + " result C"];

liveSearchInput?.addEventListener("input", () => {
  clearTimeout(liveSearchTimeout);
  liveSearchTimeout = setTimeout(() => {
    const results = liveSearchInput.value ? mockSearch(liveSearchInput.value) : [];
    if (!liveSearchResults) return;
    liveSearchResults.innerHTML = results.map((result) => "<li>" + result + "</li>").join("");
  }, 250);
});
Pagination

Render page controls and slice current items.

Showing page 1 of 6
const paginationInfo = document.querySelector("#paginationInfo");
const prevPage = document.querySelector("#prevPage");
const nextPage = document.querySelector("#nextPage");
const totalPages = 6;
let currentPage = 1;

const renderPage = () => {
  if (paginationInfo) paginationInfo.textContent = "Page " + currentPage + " of " + totalPages;
};

prevPage?.addEventListener("click", () => {
  currentPage = Math.max(1, currentPage - 1);
  renderPage();
});

nextPage?.addEventListener("click", () => {
  currentPage = Math.min(totalPages, currentPage + 1);
  renderPage();
});

renderPage();
Drag & Drop

HTML5 drag events for a reorderable list.

  • Design
  • Build
  • Ship
  • Iterate
const dragItems = [...document.querySelectorAll("#dragList li")];
let draggedIndex = null;

dragItems.forEach((item, index) => {
  item.addEventListener("dragstart", () => {
    draggedIndex = index;
  });

  item.addEventListener("dragover", (event) => {
    event.preventDefault();
  });

  item.addEventListener("drop", () => {
    const list = document.querySelector("#dragList");
    const orderedItems = [...document.querySelectorAll("#dragList li")];
    const draggedItem = orderedItems[draggedIndex];
    if (draggedItem && list) list.insertBefore(draggedItem, orderedItems[index]);
  });
});
File Upload Preview

Read multi-file input into a list with sizes.

const fileInput = document.querySelector("#fileInput");
const fileList = document.querySelector("#fileList");

fileInput?.addEventListener("change", () => {
  const files = [...(fileInput.files || [])];
  if (!fileList) return;
  fileList.innerHTML = files
    .map((file) => "<li>" + file.name + " - " + Math.round(file.size / 1024) + " KB</li>")
    .join("");
});
Image Preview Before Upload

Use URL.createObjectURL for instant preview.

const imageInput = document.querySelector("#imageInput");
const imagePreview = document.querySelector("#imagePreview");

imageInput?.addEventListener("change", () => {
  const [file] = imageInput.files || [];
  if (!file || !imagePreview) return;
  imagePreview.src = URL.createObjectURL(file);
});
Character Counter

Enforce & display a max-length count.

0 / 140
const tweetInput = document.querySelector("#tweetInput");
const tweetCounter = document.querySelector("#tweetCounter");

tweetInput?.addEventListener("input", () => {
  const length = tweetInput.value.length;
  if (tweetCounter) tweetCounter.textContent = length + " / 140";
});
Countdown Timer

Count down d/h/m/s to a target date.

56d 11:33:19
const countdownValue = document.querySelector("#countdownValue");
const countdownTarget = new Date("2027-01-01T00:00:00").getTime();

const renderCountdown = () => {
  const diff = Math.max(0, countdownTarget - Date.now());
  const days = Math.floor(diff / 86400000);
  const hours = Math.floor(diff / 3600000) % 24;
  const minutes = Math.floor(diff / 60000) % 60;
  const seconds = Math.floor(diff / 1000) % 60;

  if (countdownValue) {
    countdownValue.textContent = `${days}d ${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
  }
};

renderCountdown();
setInterval(renderCountdown, 1000);
Stopwatch

Start / pause / reset with millisecond accuracy.

00:00.00
const stopwatchValue = document.querySelector("#stopwatchValue");
const startStopwatch = document.querySelector("#startStopwatch");
const pauseStopwatch = document.querySelector("#pauseStopwatch");
const resetStopwatch = document.querySelector("#resetStopwatch");

let elapsed = 0;
let timerId = null;

const formatTime = (value) => {
  const minutes = String(Math.floor(value / 60000)).padStart(2, "0");
  const seconds = String(Math.floor(value / 1000) % 60).padStart(2, "0");
  const hundredths = String(Math.floor(value / 10) % 100).padStart(2, "0");
  return `${minutes}:${seconds}.${hundredths}`;
};

const renderStopwatch = () => {
  if (stopwatchValue) stopwatchValue.textContent = formatTime(elapsed);
};

startStopwatch?.addEventListener("click", () => {
  if (timerId) return;
  timerId = setInterval(() => {
    elapsed += 10;
    renderStopwatch();
  }, 10);
});

pauseStopwatch?.addEventListener("click", () => {
  clearInterval(timerId);
  timerId = null;
});

resetStopwatch?.addEventListener("click", () => {
  clearInterval(timerId);
  timerId = null;
  elapsed = 0;
  renderStopwatch();
});

renderStopwatch();
Digital Clock

Live time updated every second.

--:--:--
const clockValue = document.querySelector("#clockValue");

const renderClock = () => {
  if (clockValue) clockValue.textContent = new Date().toLocaleTimeString();
};

renderClock();
setInterval(renderClock, 1000);
Random Color Generator

Random hex color one-liner.

#22c55e
const colorPreview = document.querySelector("#colorPreview");
const colorValue = document.querySelector("#colorValue");
const rollColor = document.querySelector("#rollColor");

rollColor?.addEventListener("click", () => {
  const color = "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0");
  if (colorPreview) colorPreview.style.background = color;
  if (colorValue) colorValue.textContent = color;
});
Random Quote Generator

Pick a random quote from an array.

“Ship it.”
const quoteText = document.querySelector("#quoteText");
const newQuote = document.querySelector("#newQuote");
const quotes = [
  "Ship it.",
  "Details matter.",
  "Design in the browser.",
  "Make it work, then make it beautiful.",
];

newQuote?.addEventListener("click", () => {
  const quote = quotes[Math.floor(Math.random() * quotes.length)];
  if (quoteText) quoteText.textContent = quote;
});
UUID Generator

Native crypto.randomUUID() — no library needed.

click generate
const uuidValue = document.querySelector("#uuidValue");
const generateUuid = document.querySelector("#generateUuid");

generateUuid?.addEventListener("click", () => {
  const uuid = crypto.randomUUID();
  if (uuidValue) uuidValue.textContent = uuid;
});
Event Delegation

Use one parent listener to handle many child actions.

const taskList = document.querySelector("#taskList");

taskList?.addEventListener("click", (event) => {
  const button = event.target.closest("[data-task]");
  if (!button) return;
  button.classList.toggle("is-done");
  console.log("Clicked:", button.dataset.task);
});
LocalStorage Form Saver

Autosave a draft locally while the user types.

const draftInput = document.querySelector("#draftInput");
const draftKey = "draft-message";

if (draftInput) draftInput.value = localStorage.getItem(draftKey) || "";

draftInput?.addEventListener("input", () => {
  localStorage.setItem(draftKey, draftInput.value);
});
Query Params Reader

Read URL search params as a plain object.

{ "role": "frontend", "mode": "remote" }
const urlInput = document.querySelector("#urlInput");
const paramsOutput = document.querySelector("#paramsOutput");

const renderParams = () => {
  const url = new URL(urlInput.value);
  const params = Object.fromEntries(url.searchParams.entries());
  if (paramsOutput) paramsOutput.textContent = JSON.stringify(params, null, 2);
};

urlInput?.addEventListener("input", renderParams);
renderParams();
Download Text File

Generate a text file and download it in the browser.

const downloadFile = document.querySelector("#downloadFile");

downloadFile?.addEventListener("click", () => {
  const blob = new Blob(["Hello from vanilla JS"], { type: "text/plain" });
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "snippet-demo.txt";
  link.click();
  URL.revokeObjectURL(link.href);
});
FormData to JSON

Serialize form fields into a clean JSON-ready object.

{}
const profileForm = document.querySelector("#profileForm");
const formDataOutput = document.querySelector("#formDataOutput");

profileForm?.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = Object.fromEntries(new FormData(profileForm).entries());
  if (formDataOutput) formDataOutput.textContent = JSON.stringify(data, null, 2);
});
Custom Event Bus

Dispatch and subscribe to your own browser events.

Waiting...
const dispatchCustomEvent = document.querySelector("#dispatchCustomEvent");
const customEventOutput = document.querySelector("#customEventOutput");

window.addEventListener("snippet:notify", (event) => {
  if (customEventOutput) customEventOutput.textContent = event.detail;
});

dispatchCustomEvent?.addEventListener("click", () => {
  window.dispatchEvent(new CustomEvent("snippet:notify", {
    detail: "Custom event fired",
  }));
});
Array Map Transformation

A common interview starter for transforming arrays immutably.

{
  "nums": [
    1,
    2,
    3,
    4
  ],
  "doubled": [
    2,
    4,
    6,
    8
  ]
}
const mapOutput = document.querySelector("#mapOutput");
const nums = [1, 2, 3, 4];
const doubled = nums.map((num) => num * 2);

if (mapOutput) {
  mapOutput.textContent = JSON.stringify({ nums, doubled }, null, 2);
}
Array Reduce Sum

Use reduce to aggregate values into a single result.

[120, 80, 50, 30]
280
const reduceOutput = document.querySelector("#reduceOutput");
const prices = [120, 80, 50, 30];
const total = prices.reduce((sum, price) => sum + price, 0);

if (reduceOutput) reduceOutput.textContent = String(total);
Promise.all Runner

Resolve multiple async tasks in parallel.

Idle
const runPromiseAll = document.querySelector("#runPromiseAll");
const promiseAllOutput = document.querySelector("#promiseAllOutput");

const wait = (label, ms) => new Promise((resolve) => {
  setTimeout(() => resolve(label), ms);
});

runPromiseAll?.addEventListener("click", async () => {
  if (promiseAllOutput) promiseAllOutput.textContent = "Loading...";
  const result = await Promise.all([
    wait("users", 400),
    wait("posts", 650),
    wait("comments", 250),
  ]);
  if (promiseAllOutput) promiseAllOutput.textContent = result.join(", ");
});
Memoized Fibonacci

Show memoization with a recursive function and cache.

Click to compute
const memoFib = document.querySelector("#memoFib");
const memoFibOutput = document.querySelector("#memoFibOutput");

const fib = (n, cache = new Map()) => {
  if (cache.has(n)) return cache.get(n);
  if (n < 2) return n;
  const result = fib(n - 1, cache) + fib(n - 2, cache);
  cache.set(n, result);
  return result;
};

memoFib?.addEventListener("click", () => {
  if (memoFibOutput) memoFibOutput.textContent = String(fib(20));
});
Flatten Nested Array

Flatten nested arrays using modern JavaScript.

{
  "nested": [
    1,
    [
      2,
      3
    ],
    [
      4,
      [
        5,
        6
      ]
    ]
  ],
  "flat": [
    1,
    2,
    3,
    4,
    5,
    6
  ]
}
const flatOutput = document.querySelector("#flatOutput");
const nested = [1, [2, 3], [4, [5, 6]]];
const flat = nested.flat(2);

if (flatOutput) {
  flatOutput.textContent = JSON.stringify({ nested, flat }, null, 2);
}
Group By Property

Group arrays of objects by a property key.

{
  "library": [
    {
      "name": "React",
      "type": "library"
    }
  ],
  "framework": [
    {
      "name": "Vue",
      "type": "framework"
    },
    {
      "name": "Next.js",
      "type": "framework"
    }
  ]
}
const groupOutput = document.querySelector("#groupOutput");
const items = [
  { name: "React", type: "library" },
  { name: "Vue", type: "framework" },
  { name: "Next.js", type: "framework" },
];

const grouped = items.reduce((acc, item) => {
  (acc[item.type] ||= []).push(item);
  return acc;
}, {});

if (groupOutput) groupOutput.textContent = JSON.stringify(grouped, null, 2);
Retry Async Request

Wrap flaky async calls with a retry helper.

Not started
const retryDemo = document.querySelector("#retryDemo");
const retryOutput = document.querySelector("#retryOutput");

retryDemo?.addEventListener("click", async () => {
  let attempts = 0;

  const fakeRequest = () => new Promise((resolve, reject) => {
    attempts += 1;
    if (attempts < 3) reject(new Error("fail"));
    else resolve("success");
  });

  const retry = async (fn, maxRetries = 3) => {
    let lastError;
    for (let i = 0; i < maxRetries; i += 1) {
      try {
        return await fn();
      } catch (error) {
        lastError = error;
      }
    }
    throw lastError;
  };

  const result = await retry(fakeRequest);
  if (retryOutput) retryOutput.textContent = `Succeeded on try ${attempts}: ${result}`;
});
Deep Clone Object

Use structuredClone for safe deep copies.

{
  "original": {
    "user": {
      "name": "JB"
    },
    "skills": [
      "JS",
      "React"
    ]
  },
  "copy": {
    "user": {
      "name": "Cloned"
    },
    "skills": [
      "JS",
      "React"
    ]
  }
}
const cloneOutput = document.querySelector("#cloneOutput");
const original = { user: { name: "JB" }, skills: ["JS", "React"] };
const copy = structuredClone(original);
copy.user.name = "Cloned";

if (cloneOutput) {
  cloneOutput.textContent = JSON.stringify({ original, copy }, null, 2);
}
Sort Objects by Key

Sort object arrays by a numeric property.

[
  {
    "name": "Aman",
    "years": 8
  },
  {
    "name": "Riya",
    "years": 6
  },
  {
    "name": "Zara",
    "years": 4
  }
]
const sortOutput = document.querySelector("#sortOutput");
const people = [
  { name: "Zara", years: 4 },
  { name: "Aman", years: 8 },
  { name: "Riya", years: 6 },
];

const sorted = [...people].sort((a, b) => b.years - a.years);
if (sortOutput) sortOutput.textContent = JSON.stringify(sorted, null, 2);
Once Function Wrapper

Create a helper that only allows a callback once.

count: 0
const onceButton = document.querySelector("#onceButton");
const onceOutput = document.querySelector("#onceOutput");

const once = (fn) => {
  let called = false;
  return (...args) => {
    if (called) return;
    called = true;
    fn(...args);
  };
};

let count = 0;
const updateOnce = once(() => {
  count += 1;
  if (onceOutput) onceOutput.textContent = "count: " + count;
});

onceButton?.addEventListener("click", updateOnce);
Closure Counter

Classic interview example for closures retaining private state.

0
document.addEventListener("DOMContentLoaded", () => {
  const createCounter = () => {
    let count = 0;
    return () => ++count;
  };
  const counter = createCounter();
});
Currying Function

Convert multi-argument logic into chained unary functions.

{
  "add5": "const add5 = add(5)",
  "result": 8
}
document.addEventListener("DOMContentLoaded", () => {
  const add = (a) => (b) => a + b;
  const add5 = add(5);
  console.log(add5(3));
});
Pipe Function

Compose small functions left-to-right for cleaner transformations.

pipe(add2, times3, minus1)(4)
17
document.addEventListener("DOMContentLoaded", () => {
  const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);
  const result = pipe(add2, times3, minus1)(4);
});
Binary Search

Efficiently search sorted arrays in O(log n).

{
  "arr": [
    2,
    4,
    6,
    8,
    10,
    12,
    14
  ],
  "target": 10,
  "index": 4
}
document.addEventListener("DOMContentLoaded", () => {
  let left = 0;
  let right = arr.length - 1;
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
});
Tree DFS Traversal

Depth-first recursion over nested node structures.

{
  "traversal": [
    "A",
    "B",
    "D",
    "C"
  ]
}
document.addEventListener("DOMContentLoaded", () => {
  const dfs = (node) => {
    result.push(node.value);
    node.children.forEach(dfs);
  };
});
Event Loop Order

Show sync code, microtasks, and macrotasks execution order.

    document.addEventListener("DOMContentLoaded", () => {
      console.log("script start");
      Promise.resolve().then(() => console.log("microtask"));
      setTimeout(() => console.log("macrotask"), 0);
      console.log("script end");
    });
    Array.map Polyfill Idea

    Understand how mapping works internally using iteration.

    {
      "input": [
        1,
        2,
        3
      ],
      "mapped": [
        2,
        4,
        6
      ]
    }
    document.addEventListener("DOMContentLoaded", () => {
      const mapped = arr.reduce((acc, item) => {
        acc.push(item * 2);
        return acc;
      }, []);
    });
    Function.bind Example

    Lock a function's `this` context and preset arguments.

    Hi, I'm Jwala the developer
    document.addEventListener("DOMContentLoaded", () => {
      function greet(role) {
        return `Hi, I'm ${this.name} the ${role}`;
      }
      const bound = greet.bind(person, "developer");
    });
    Call / Apply / Bind

    Compare the three core ways to control function context.

    {
      "call": "JB from Mumbai",
      "apply": "JB from Pune",
      "bind": "JB from Delhi"
    }
    document.addEventListener("DOMContentLoaded", () => {
      intro.call(person, "Mumbai");
      intro.apply(person, ["Pune"]);
      intro.bind(person, "Delhi")();
    });
    Tiny LRU Cache

    Useful interview pattern using Map insertion order.

    empty
    document.addEventListener("DOMContentLoaded", () => {
      const cache = new Map();
      if (cache.has(key)) cache.delete(key);
      cache.set(key, value);
      if (cache.size > limit) cache.delete(cache.keys().next().value);
    });

    How To Use It

    1. 1Paste code, JSON, markup, or the input the tool needs.
    2. 2Adjust the options and watch the output update live.
    3. 3Copy the generated code and drop it into your project.

    Related Tools

    More tools from the same category, so you can keep moving without going back to the full index.

    Browse all
    Quick nav
    JavaScript Snippets - 70 Ready-made
    JavaScript