Frontend Development 8 min read

Useful JavaScript Code Snippets for Common Front‑End Tasks

This article provides a collection of practical JavaScript snippets covering cookie handling, color conversion, clipboard operations, date validation, string manipulation, array utilities, URL query extraction, time formatting, and dark‑mode detection, all useful for front‑end developers.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Useful JavaScript Code Snippets for Common Front‑End Tasks

Get Browser Cookie Value

Use document.cookie to retrieve a specific cookie value.

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

cookie('_ga'); // Result: "GA1.2.1929736587.1601974046"

Convert RGB Color to Hexadecimal

Transform RGB components into a hex string.

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(0, 51, 255); // Result: #0033ff

Copy Text to Clipboard

Leverage navigator.clipboard.writeText to copy a string.

const copyToClipboard = text => navigator.clipboard.writeText(text);

copyToClipboard("Hello World");

Validate Date Legitimacy

Check whether a given date string can be parsed into a valid Date object.

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 17, 1995 03:24:00"); // Result: true

Find Day of Year

Calculate which day of the year a date falls on.

const dayOfYear = date => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date()); // Result: 272 (example)

Capitalize First Letter of a String

JavaScript lacks a built‑in method, so use a custom function.

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);

capitalize("follow for more"); // Result: Follow for more

Calculate Days Between Two Dates

Return the absolute difference in days.

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);

dayDif(new Date("2020-10-21"), new Date("2021-10-22")); // Result: 366

Clear All Cookies

Iterate over document.cookie and set each cookie’s expiration to the past.

const clearCookies = document.cookie.split(';').forEach(cookie =>
  document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)
);

Generate Random Hexadecimal Color

Combine Math.random with padEnd to produce a random hex code.

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

console.log(randomHex()); // Result: #92b008

Array Deduplication

Use a Set to remove duplicate elements.

const removeDuplicates = arr => [...new Set(arr)];

console.log(removeDuplicates([1,2,3,3,4,4,5,5,6])); // Result: [1,2,3,4,5,6]

Get URL Query Parameters

Parse the query string manually or with URLSearchParams for a concise solution.

const getParameters = URL => {
  URL = JSON.parse('{"' +
    decodeURI(URL.split("?")[1])
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"') +
    '"}');
  return JSON.stringify(URL);
};

getParameters(window.location); // Result: { search : "easy", page : 3 }

// Simpler version:
Object.fromEntries(new URLSearchParams(window.location.search));

Time Formatting

Extract hh:mm:ss from a Date object.

const timeFromDate = date => date.toTimeString().slice(0, 8);

console.log(timeFromDate(new Date(2021,0,10,17,30,0))); // Result: "17:30:00"

Check If Number Is Even

Simple modulus test.

const isEven = num => num % 2 === 0;

console.log(isEven(2)); // Result: True

Calculate Average of Numbers

Use reduce to sum values and divide by count.

const average = (...args) => args.reduce((a,b) => a + b) / args.length;

average(1,2,3,4); // Result: 2.5

Scroll Back to Top

Invoke window.scrollTo(0, 0) to jump to the top of the page.

const goToTop = () => window.scrollTo(0, 0);

goToTop();

Reverse a String

Combine split , reverse , and join .

const reverse = str => str.split('').reverse().join('');

reverse('hello world'); // Result: 'dlrow olleh'

Check If Array Is Empty

One‑liner returning a boolean.

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1,2,3]); // Result: true

Get User‑Selected Text

Use the getSelection API.

const getSelectedText = () => window.getSelection().toString();

getSelectedText();

Shuffle an Array

Sort with a random comparator.

const shuffleArray = arr => arr.sort(() => 0.5 - Math.random());

console.log(shuffleArray([1,2,3,4])); // Result: [1,4,3,2] (example)

Detect Dark Mode Preference

Query the prefers-color-scheme media feature.

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

console.log(isDarkMode); // Result: True or False
frontendJavaScriptWeb Developmentcode snippetsbrowser APIutilities
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login 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.