Master 48 Essential JavaScript Snippets in 30 Seconds
This article presents a curated collection of 48 practical JavaScript utilities—from generating anagrams and calculating averages to deep‑flattening arrays and creating UUIDs—each explained in a concise description with ready‑to‑use code examples for front‑end developers.
The project, created by GitHub user Chalarangelo , has earned over 5,000 stars and gathers 48 useful JavaScript code snippets that can be understood in 30 seconds or less.
Anagrams of string (with duplicates)
Generate all anagrams of a string, handling duplicate characters, using recursion, map() and reduce().
const anagrams = str => {
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str.split('').reduce((acc, letter, i) =>
acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), []);
};
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']Array average
Calculate the average of an array using reduce().
const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
// average([1,2,3]) -> 2Capitalize every word
Upper‑case the first letter of each word with replace() and toUpperCase().
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
// capitalizeEveryWord('hello world!') -> 'Hello World!'Capitalize first letter
Upper‑case the first character of a string, optionally lower‑casing the rest.
const capitalize = (str, lowerRest = false) =>
str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
// capitalize('myName', true) -> 'Myname'Check palindrome
Determine if a string is a palindrome by normalising case and removing non‑letters.
const palindrome = str => {
const s = str.toLowerCase().replace(/[\W_]/g,'');
return s === s.split('').reverse().join('');
};
// palindrome('taco cat') -> trueCount occurrences in array
Count how many times a specific value appears in an array using reduce().
const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a, 0);
// countOccurrences([1,1,2,1,2,3], 1) -> 3Current URL
Retrieve the current page URL.
const currentUrl = _ => window.location.href;
// currentUrl() -> 'https://google.com'Curry
Create a curried version of a function that collects arguments until the required arity is met.
const curry = (fn, arity = fn.length, ...args) =>
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
// curry(Math.pow)(2)(10) -> 1024
// curry(Math.min, 3)(10)(50)(2) -> 2Deep flatten array
Recursively flatten nested arrays.
const deepFlatten = arr =>
arr.reduce((a, v) => a.concat(Array.isArray(v) ? deepFlatten(v) : v), []);
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]Array difference
Return values present in the first array but not in the second.
const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); };
// difference([1,2,3], [1,2]) -> [3]Distance between two points
Calculate Euclidean distance using Math.hypot().
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
// distance(1,1, 2,3) -> 2.23606797749979Divisible by number
Check if a dividend is evenly divisible by a divisor.
const isDivisible = (dividend, divisor) => dividend % divisor === 0;
// isDivisible(6,3) -> trueEscape RegExp
Escape special characters in a string for use in a regular expression.
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// escapeRegExp('(test)') -> '\\(test\\)'Even or odd
Return true for even numbers, false for odd.
const isEven = num => num % 2 === 0;
// isEven(3) -> falseFactorial
Compute factorial recursively.
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
// factorial(6) -> 720Fibonacci array generator
Create an array of Fibonacci numbers of length n.
const fibonacci = n =>
Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
// fibonacci(5) -> [0,1,1,2,3]Filter non‑unique values
Return only values that appear once in an array.
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]Flatten array
Flatten one level of nesting using reduce() and concat().
const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
// flatten([1,[2],3,4]) -> [1,2,3,4]Array max / min
Find the maximum or minimum value in an array with the spread operator.
const arrayMax = arr => Math.max(...arr);
// arrayMax([10, 1, 5]) -> 10
const arrayMin = arr => Math.min(...arr);
// arrayMin([10, 1, 5]) -> 1Scroll to top
Smoothly scroll the page to the top using requestAnimationFrame.
const scrollToTop = _ => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
// scrollToTop()Shuffle array
Randomly reorder an array.
const shuffle = arr => arr.sort(() => Math.random() - 0.5);
// shuffle([1,2,3]) -> [2,3,1]Redirect to URL
Redirect the browser to a new URL, optionally simulating a link click.
const redirect = (url, asLink = true) =>
asLink ? window.location.href = url : window.location.replace(url);
// redirect('https://google.com')Reverse string
Reverse the characters of a string.
const reverseString = str => [...str].reverse().join('');
// reverseString('foobar') -> 'raboof'RGB to hex
Convert RGB values to a six‑digit hexadecimal string.
const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
// rgbToHex(255, 165, 1) -> 'ffa501'Swap variables
Swap two variables using array destructuring.
[varA, varB] = [varB, varA];
// [x, y] = [y, x]UUID generator
Generate a RFC‑4122 version‑4 UUID using the Crypto API.
const uuid = _ =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'Note: Translations may contain minor inaccuracies; interested developers should refer to the original English source on GitHub.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
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.
