12 Essential JavaScript Snippets Every Front‑End Developer Should Know

This article compiles twelve practical JavaScript functions—from generating random colors and shuffling arrays to detecting dark mode, scrolling, clipboard copying, device detection, element visibility, URL parameters, deep cloning, and async waiting—each explained with concise code examples for everyday front‑end development.

21CTO
21CTO
21CTO
12 Essential JavaScript Snippets Every Front‑End Developer Should Know

1. Generate Random Color

Quickly create a random hexadecimal color string.

const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
console.log(generateRandomHexColor());

2. Shuffle Array

Reorder an array's elements using a simple random sort.

const shuffle = (arr) => arr.sort(() => Math.random() - 0.5);
const arr = [1, 2, 3, 4, 5];
console.log(shuffle(arr));

3. Copy to Clipboard

Copy a text string to the user's clipboard.

const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text);
copyToClipboard("Hello World!");

4. Detect Dark Mode

Check whether the user prefers a dark color scheme.

const isDarkMode = () => window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
console.log(isDarkMode());

5. Scroll to Top

Smoothly scroll an element to the top of its scroll container.

const scrollToTop = (element) => {
  element.scrollIntoView({ behavior: "smooth", block: "start" });
};

6. Scroll to Bottom

Smoothly scroll an element to the bottom of its scroll container.

const scrollToBottom = (element) => {
  element.scrollIntoView({ behavior: "smooth", block: "end" });
};

7. Detect Element Visibility

Use IntersectionObserver to know when an element enters the viewport.

const callback = (entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      console.log(`${entry.target.id} is visible`);
    }
  });
};
const options = { threshold: 1.0 };
const observer = new IntersectionObserver(callback, options);
const btn = document.getElementById("btn");
const bottomBtn = document.getElementById("bottom-btn");
observer.observe(btn);
observer.observe(bottomBtn);

8. Detect Device Type

Identify whether the current platform is mobile or desktop.

const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
console.log(detectDeviceType());

9. Hide Element

Toggle an element's visibility or completely remove it from the layout.

const hideElement = (el, removeFromFlow = false) => {
  removeFromFlow ? (el.style.display = 'none') : (el.style.visibility = 'hidden');
};

10. Get URL Parameter

Extract a query parameter value from the current page URL.

const getParamByUrl = (key) => {
  const url = new URL(location.href);
  return url.searchParams.get(key);
};

11. Deep Clone Object

Create a deep copy of an object using JSON methods or the newer structuredClone API.

const deepCopy = (obj) => JSON.parse(JSON.stringify(obj));
// Modern alternative (browser support may vary)
structuredClone(obj);

12. Wait Function for Async Code

Wrap setTimeout in a Promise to use with async/await.

const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const asyncFn = async () => {
  await wait(1000);
  console.log('等待异步函数执行结束');
};
asyncFn();
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendJavaScriptWeb Developmentcode snippetsutilities
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.