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.
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.
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.
Native smooth scrolling to any element.
const scrollButton = document.querySelector(".scroll-btn");
const pricingSection = document.querySelector("#pricing");
scrollButton?.addEventListener("click", () => {
pricingSection?.scrollIntoView({
behavior: "smooth",
block: "start",
});
});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" });
});CSS position:sticky keeps nav pinned during scroll.
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));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");
});
});Reflect page scroll % as a horizontal bar.
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 + "%";
});Animate elements when they enter the viewport.
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));Native browser lazy loading — no JS needed.
const lazyImage = document.querySelector(".lazy-image");
lazyImage?.addEventListener("load", () => {
lazyImage.classList.add("is-loaded");
});Load more items when a sentinel enters view.
- item #1
- item #2
- item #3
- item #4
- item #5
- item #6
- item #7
- item #8
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);Toggle a `dark` class on <html>.
Currently: light
const themeToggle = document.querySelector("#themeToggle");
themeToggle?.addEventListener("click", () => {
document.documentElement.classList.toggle("dark");
});Persist user's theme choice across reloads.
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);
});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();
});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);
});Toggle expandable panels, one open at a time.
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");
});
});Switch content panels via tab buttons.
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");
});
});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");
});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));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)));
});Manual slider with dot indicators.
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-advance items on an interval.
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);Animate a number to a target on click.
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);
});Smooth easing with requestAnimationFrame.
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();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);Randomize characters, then settle on target.
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);Expand/collapse long text blocks.
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";
});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";
});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";
});Score password against length + variety rules.
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];
});Regex-based email validator with live feedback.
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";
}
});Delay a function until N ms after the last call.
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);
});Run a function at most once every N ms.
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);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";
}
});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;
});
});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);
});Render page controls and slice current items.
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();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]);
});
});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("");
});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);
});Enforce & display a max-length count.
const tweetInput = document.querySelector("#tweetInput");
const tweetCounter = document.querySelector("#tweetCounter");
tweetInput?.addEventListener("input", () => {
const length = tweetInput.value.length;
if (tweetCounter) tweetCounter.textContent = length + " / 140";
});Count down d/h/m/s to a target date.
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);Start / pause / reset with millisecond accuracy.
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();Live time updated every second.
const clockValue = document.querySelector("#clockValue");
const renderClock = () => {
if (clockValue) clockValue.textContent = new Date().toLocaleTimeString();
};
renderClock();
setInterval(renderClock, 1000);Random hex color one-liner.
#22c55econst 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;
});Pick a random quote from an array.
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;
});Native crypto.randomUUID() — no library needed.
click generateconst uuidValue = document.querySelector("#uuidValue");
const generateUuid = document.querySelector("#generateUuid");
generateUuid?.addEventListener("click", () => {
const uuid = crypto.randomUUID();
if (uuidValue) uuidValue.textContent = uuid;
});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);
});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);
});Read URL search params as a plain object.
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();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);
});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);
});Dispatch and subscribe to your own browser events.
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",
}));
});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);
}Use reduce to aggregate values into a single result.
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);Resolve multiple async tasks in parallel.
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(", ");
});Show memoization with a recursive function and cache.
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 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 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);Wrap flaky async calls with a retry helper.
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}`;
});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 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);Create a helper that only allows a callback once.
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);Classic interview example for closures retaining private state.
document.addEventListener("DOMContentLoaded", () => {
const createCounter = () => {
let count = 0;
return () => ++count;
};
const counter = createCounter();
});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));
});Compose small functions left-to-right for cleaner transformations.
document.addEventListener("DOMContentLoaded", () => {
const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);
const result = pipe(add2, times3, minus1)(4);
});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;
}
});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);
};
});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");
});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;
}, []);
});Lock a function's `this` context and preset arguments.
document.addEventListener("DOMContentLoaded", () => {
function greet(role) {
return `Hi, I'm ${this.name} the ${role}`;
}
const bound = greet.bind(person, "developer");
});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")();
});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
- 1Paste code, JSON, markup, or the input the tool needs.
- 2Adjust the options and watch the output update live.
- 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.