20 JavaScript One‑Liner Tricks for Frontend Development
This article presents twenty concise JavaScript one‑liner snippets that boost front‑end productivity, covering tasks such as retrieving cookies, converting RGB to hex, copying to clipboard, validating dates, calculating day differences, manipulating strings, arrays, and detecting dark mode, each illustrated with ready‑to‑use code examples.
This article compiles twenty practical JavaScript one‑liner tricks aimed at improving front‑end development efficiency. Each trick includes a brief description and a ready‑to‑copy code snippet.
Get Browser Cookie Value
Use document.cookie to retrieve the value of a specific cookie.
const cookie = name => `;${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga'); // Result: "GA1.2.1929736587.1601974046"Convert RGB to Hex
Convert RGB color components to a hexadecimal string.
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(0, 51, 255); // Result: #0033ffCopy to Clipboard
Use navigator.clipboard.writeText to copy text to the clipboard.
const copyToClipboard = text => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");Check If Date Is Valid
Validate a date string using Date and Number.isNaN .
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00"); // Result: trueFind Day of Year
Calculate which day of the year a given date falls on.
const dayOfYear = date => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // Result: 272Capitalize String
Transform the first character of a string to uppercase.
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
capitalize("follow for more"); // Result: Follow for moreCalculate Days Between Two Dates
Compute the absolute number of days between two dates.
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: 366Clear All Cookies
Remove all cookies by setting their expiration date to the past.
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));Generate Random Hex Color
Create a random hexadecimal color string using Math.random and padEnd .
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex()); // Result: #92b008Remove Duplicates From Array
Eliminate duplicate values in an array using Set .
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 query parameters from a URL string.
const getParameters = URL => {
URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + "}"});
return JSON.stringify(URL);
};Extract Time From Date
Format a date object to hh:mm:ss using toTimeString .
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
Determine whether a number is even.
const isEven = num => num % 2 === 0;
console.log(isEven(2)); // Result: TrueCalculate Average of Numbers
Use reduce to compute the average of multiple numbers.
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4); // Result: 2.5Scroll to Top
Automatically scroll the page to the top.
const goToTop = () => window.scrollTo(0, 0);
goToTop();Reverse String
Reverse a string using split , reverse , and join .
const reverse = str => str.split('').reverse().join('');
reverse('hello world'); // Result: 'dlrow olleh'Check If Array Is Not Empty
Return true if an array exists and contains elements.
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1,2,3]); // Result: trueGet Selected Text
Retrieve the currently selected text in the browser.
const getSelectedText = () => window.getSelection().toString();
getSelectedText();Shuffle Array
Randomly reorder an array's elements.
const shuffleArray = arr => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1,2,3,4])); // Result: [ 1, 4, 3, 2 ]Detect Dark Mode
Check whether the user's system prefers a dark color scheme.
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
console.log(isDarkMode); // Result: True or FalseThe article concludes after presenting all twenty one‑liner tricks, hoping they help readers streamline daily front‑end tasks.
HomeTech
HomeTech tech sharing
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.