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().
<code>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']
</code>Array average
Calculate the average of an array using
reduce().
<code>const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
// average([1,2,3]) -> 2
</code>Capitalize every word
Upper‑case the first letter of each word with
replace()and
toUpperCase().
<code>const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
// capitalizeEveryWord('hello world!') -> 'Hello World!'
</code>Capitalize first letter
Upper‑case the first character of a string, optionally lower‑casing the rest.
<code>const capitalize = (str, lowerRest = false) =>
str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
// capitalize('myName', true) -> 'Myname'
</code>Check palindrome
Determine if a string is a palindrome by normalising case and removing non‑letters.
<code>const palindrome = str => {
const s = str.toLowerCase().replace(/[\W_]/g,'');
return s === s.split('').reverse().join('');
};
// palindrome('taco cat') -> true
</code>Count occurrences in array
Count how many times a specific value appears in an array using
reduce().
<code>const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a, 0);
// countOccurrences([1,1,2,1,2,3], 1) -> 3
</code>Current URL
Retrieve the current page URL.
<code>const currentUrl = _ => window.location.href;
// currentUrl() -> 'https://google.com'
</code>Curry
Create a curried version of a function that collects arguments until the required arity is met.
<code>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) -> 2
</code>Deep flatten array
Recursively flatten nested arrays.
<code>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]
</code>Array difference
Return values present in the first array but not in the second.
<code>const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); };
// difference([1,2,3], [1,2]) -> [3]
</code>Distance between two points
Calculate Euclidean distance using
Math.hypot().
<code>const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
// distance(1,1, 2,3) -> 2.23606797749979
</code>Divisible by number
Check if a dividend is evenly divisible by a divisor.
<code>const isDivisible = (dividend, divisor) => dividend % divisor === 0;
// isDivisible(6,3) -> true
</code>Escape RegExp
Escape special characters in a string for use in a regular expression.
<code>const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// escapeRegExp('(test)') -> '\\(test\\)'
</code>Even or odd
Return
truefor even numbers,
falsefor odd.
<code>const isEven = num => num % 2 === 0;
// isEven(3) -> false
</code>Factorial
Compute factorial recursively.
<code>const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
// factorial(6) -> 720
</code>Fibonacci array generator
Create an array of Fibonacci numbers of length
n.
<code>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]
</code>Filter non‑unique values
Return only values that appear once in an array.
<code>const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]
</code>Flatten array
Flatten one level of nesting using
reduce()and
concat().
<code>const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
// flatten([1,[2],3,4]) -> [1,2,3,4]
</code>Array max / min
Find the maximum or minimum value in an array with the spread operator.
<code>const arrayMax = arr => Math.max(...arr);
// arrayMax([10, 1, 5]) -> 10
const arrayMin = arr => Math.min(...arr);
// arrayMin([10, 1, 5]) -> 1
</code>Scroll to top
Smoothly scroll the page to the top using
requestAnimationFrame.
<code>const scrollToTop = _ => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
// scrollToTop()
</code>Shuffle array
Randomly reorder an array.
<code>const shuffle = arr => arr.sort(() => Math.random() - 0.5);
// shuffle([1,2,3]) -> [2,3,1]
</code>Redirect to URL
Redirect the browser to a new URL, optionally simulating a link click.
<code>const redirect = (url, asLink = true) =>
asLink ? window.location.href = url : window.location.replace(url);
// redirect('https://google.com')
</code>Reverse string
Reverse the characters of a string.
<code>const reverseString = str => [...str].reverse().join('');
// reverseString('foobar') -> 'raboof'
</code>RGB to hex
Convert RGB values to a six‑digit hexadecimal string.
<code>const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
// rgbToHex(255, 165, 1) -> 'ffa501'
</code>Swap variables
Swap two variables using array destructuring.
<code>[varA, varB] = [varB, varA];
// [x, y] = [y, x]
</code>UUID generator
Generate a RFC‑4122 version‑4 UUID using the Crypto API.
<code>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'
</code>Note: Translations may contain minor inaccuracies; interested developers should refer to the original English source on GitHub.
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.