50 Javascript Snippets you need to know right now

One of the most popular languages to learn is JavaScript. "If you're only going to learn one programming language, learn JavaScript," as many people advise. In an interview, Quincy Larson, the founder of FreeCodeCamp, was asked which language developers should learn first. "JavaScript," he replied. "The world is being eaten by software, and JavaScript is eating software." With each passing year, JavaScript gains in popularity, and no one knows what will finally replace it. If you don't have a compelling need to learn a new language (for example, if your employment requires you to maintain non-JavaScript code), my humble advice is to concentrate on improving your JavaScript skills."
If this sounds compelling to you, here are 50 Javascript snippets you can keep at your fingertips to write better code, faster.
1️⃣ all
This snippet returns true if the predicate function returns true for all elements in a collection and false otherwise. You can omit the second argument 'fn' if you want to use Boolean as a default value.
1const all = (arr, fn = Boolean) => arr.every(fn);23all([4, 2, 3], x => x > 1); // true4all([1, 2, 3]); // true
2️⃣ arrayToCSV
This snippet converts the elements to strings with comma-separated values.
1const arrayToCSV = (arr, delimiter = ',') =>2arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');34arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'5arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
3️⃣ arrayToHtmlList
This snippet converts the elements of an array into list tags and appends them to the list of the given ID.
1const arrayToHtmlList = (arr, listID) =>2(el => (3(el = document.querySelector('#' + listID)),4(el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))5))();67arrayToHtmlList(['item 1', 'item 2'], 'myListID');
4️⃣ bifurcate
This snippet splits values into two groups and then puts a truthy element of filter in the first group, and in the second group otherwise.
You can use Array.prototype.reduce() and Array.prototype.push() to add elements to groups based on filter.
1const bifurcate = (arr, filter) =>2arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);3bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]);4// [ ['beep', 'boop', 'bar'], ['foo'] ]
5️⃣ byteSize
This snippet returns the length of a string in bytes.
1const byteSize = str => new Blob([str]).size;23byteSize('😀'); // 44byteSize('Hello World'); // 11
6️⃣ capitalize
This snippet capitalizes the first letter of a string.
1const capitalize = string =>2`${string?.[0]?.toLocaleUpperCase() ?? ""}${string?.slice(1) ?? ""}`;
7️⃣ dayOfYear
This snippet gets the day of the year from a Date object.
1const dayOfYear = date =>2Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);34dayOfYear(new Date()); // 272
8️⃣ decapitalize
This snippet turns the first letter of a string into lowercase.
1const decapitalize = ([first, ...rest]) =>2first.toLowerCase() + rest.join('')34decapitalize('FooBar'); // 'fooBar'5decapitalize('FooBar'); // 'fooBar'
9️⃣ countOccurrences
This snippet counts the occurrences of a value in an array.
1const countOccurrences = value => array =>2array.filter(item => item === value).length;
🔟 default This snippet assigns default values for all properties in an object that are undefined.
1const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);23defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }
1️⃣1️⃣ allEqual This snippet checks whether all elements of the array are equal.
1const allEqual = arr => arr.every(val => val === arr[0]);23allEqual([1, 2, 3, 4, 5, 6]); // false4allEqual([1, 1, 1, 1]); // true
1️⃣2️⃣ approximatelyEqual This snippet checks whether two numbers are approximately equal to each other, with a small difference.
1const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;23approximatelyEqual(Math.PI / 2.0, 1.5708); // true
1️⃣3️⃣ attempt This snippet executes a function, returning either the result or the caught error object.
1const attempt = (fn, ...args) => {2try {3return fn(...args);4} catch (e) {5return e instanceof Error ? e : new Error(e);6}7};8var elements = attempt(function(selector) {9return document.querySelectorAll(selector);10}, '>_>');11if (elements instanceof Error) elements = []; // elements = []
1️⃣4️⃣ bifurcateBy This snippet splits values into two groups, based on a predicate function. If the predicate function returns a truthy value, the element will be placed in the first group. Otherwise, it will be placed in the second group.
You can use Array.prototype.reduce() and Array.prototype.push() to add elements to groups, based on the value returned by fn for each element.
1const bifurcateBy = (arr, fn) =>2arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);34bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b');5// [ ['beep', 'boop', 'bar'], ['foo'] ]
1️⃣5️⃣ bottomVisible This snippet checks whether the bottom of a page is visible.
1const bottomVisible = () =>2document.documentElement.clientHeight + window.scrollY >=3(document.documentElement.scrollHeight || document.documentElement.clientHeight);45bottomVisible(); // true
1️⃣6️⃣ castArray This snippet converts a non-array value into an array.
1const castArray = val => (Array.isArray(val) ? val : [val]);23castArray('foo'); // ['foo']4castArray([1]); // [1]
1️⃣7️⃣ compact This snippet removes false values from an array.
1const compact = arr => arr.filter(Boolean);23compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]);4// [ 1, 2, 3, 'a', 's', 34 ]
1️⃣8️⃣ currentURL This snippet returns the current URL.
1const currentURL = () => window.location.href;23currentURL(); // 'https://abhiraj.mdx.one'
1️⃣9️⃣ defer This snippet delays the execution of a function until the current call stack is cleared.
1const defer = (fn, ...args) => setTimeout(fn, 1, ...args);23defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
2️⃣0️⃣ degreesToRads This code snippet can be used to convert a value from degrees to radians.
1const degreesToRads = deg => (deg * Math.PI) / 180.0;23degreesToRads(90.0); // ~1.5708
2️⃣1️⃣ average This snippet returns the average of two or more numerical values.
1const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;2average(...[1, 2, 3]); // 23average(1, 2, 3); // 2
2️⃣2️⃣ averageBy This snippet returns the average of an array after initially doing the mapping of each element to a value using a given function.
1const averageBy = (arr, fn) =>2arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /3arr.length;45averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 56averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
2️⃣3️⃣ capitalizeEveryWord This snippet capitalizes the first letter of every word in a given string.
1const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());23capitalizeEveryWord('hello world!'); // 'Hello World!'
2️⃣4️⃣ Create Directory This snippet uses existsSync() to check whether a directory exists and then mkdirSync() to create it if it doesn’t.
1const fs = require('fs');2const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);3createDirIfNotExists('test');4// creates the directory 'test', if it doesn't exist
2️⃣5️⃣ deepFlatten This snippet flattens an array recursively.
1const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));23deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
2️⃣6️⃣ difference This snippet finds the difference between two arrays.
1const difference = (a, b) => {2const s = new Set(b);3return a.filter(x => !s.has(x));4};56difference([1, 2, 3], [1, 2, 4]); // [3]
2️⃣7️⃣ differenceBy This method returns the difference between two arrays, after applying a given function to each element of both lists.
1const differenceBy = (a, b, fn) => {2const s = new Set(b.map(fn));3return a.filter(x => !s.has(fn(x)));4};56differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]7differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ]
2️⃣8️⃣ differenceWith This snippet removes the values for which the comparator function returns false.
1const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);23differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b));4// [1, 1.2]
2️⃣9️⃣ digitize This snippet gets a number as input and returns an array of its digits.
1const digitize = n => [...`${n}`].map(i => parseInt(i));23digitize(431); // [4, 3, 1]
3️⃣0️⃣ distance This snippet returns the distance between two points by calculating the Euclidean distance.
1const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);23distance(1, 1, 2, 3); // 2.23606797749979
3️⃣1️⃣ Drop Elements This snippet returns a new array with n elements removed from the left.
1const drop = (arr, n = 1) => arr.slice(n);23drop([1, 2, 3]); // [2,3]4drop([1, 2, 3], 2); // [3]5drop([1, 2, 3], 42); // []
3️⃣2️⃣ dropRight This snippet returns a new array with n elements removed from the right.
1const dropRight = (arr, n = 1) => arr.slice(0, -n);23dropRight([1, 2, 3]); // [1,2]4dropRight([1, 2, 3], 2); // [1]5dropRight([1, 2, 3], 42); // []
3️⃣3️⃣ dropRightWhile This snippet removes elements from the right side of an array until the passed function returns true.
1const dropRightWhile = (arr, func) => {2while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);3return arr;4};56dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]
3️⃣4️⃣ dropWhile This snippet removes elements from an array until the passed function returns true.
1const dropWhile = (arr, func) => {2while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);3return arr;4};56dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]
3️⃣5️⃣ elementContains This snippet checks whether the parent element contains the child.
1const elementContains = (parent, child) => parent !== child && parent.contains(child);23elementContains(document.querySelector('head'), document.querySelector('title')); // true4elementContains(document.querySelector('body'), document.querySelector('body')); // false
3️⃣6️⃣ Filter Duplicate Elements This snippet removes duplicate values in an array.
1const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));23filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]
3️⃣7️⃣ findKey This snippet returns the first key that satisfies a given function.
1const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));23findKey(4{5barney: { age: 36, active: true },6fred: { age: 40, active: false },7pebbles: { age: 1, active: true }8},9o => o['active']10); // 'barney'
3️⃣8️⃣ findLast This snippet returns the last element for which a given function returns a truthy value.
1const findLast = (arr, fn) => arr.filter(fn).pop();23findLast([1, 2, 3, 4], n => n % 2 === 1); // 3
3️⃣9️⃣ insertAfter This snippet can be used to insert an HTML string after the end of a particular element.
1const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);23insertAfter(document.getElementById('myId'), '<p>after</p>'); // <div id="myId">...</div> <p>after</p>
4️⃣0️⃣ insertBefore This snippet can be used to insert an HTML string before a particular element.
1const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);23insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>
4️⃣1️⃣ flatten This snippet flattens an array up to a specified depth using recursion.
1const flatten = (arr, depth = 1) =>2arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);34flatten([1, [2], 3, 4]); // [1, 2, 3, 4]5flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
4️⃣2️⃣ forEachRight This snippet executes a function for each element of an array starting from the array’s last element.
1const forEachRight = (arr, callback) =>2arr3.slice(0)4.reverse()5.forEach(callback);67forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'
4️⃣3️⃣ forOwn This snippet iterates on each property of an object and iterates a callback for each one respectively.
1const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));2forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1
4️⃣4️⃣ Get Time From Date This snippet can be used to get the time from a Date object as a string.
1const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);23getColonTimeFromDate(new Date()); // "08:38:00"
4️⃣5️⃣ Get Days Between Dates This snippet can be used to find the difference in days between two dates.
1const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>2(dateFinal - dateInitial) / (1000 * 3600 * 24);34getDaysDiffBetweenDates(new Date('2019-01-13'), new Date('2019-01-15')); // 2
4️⃣6️⃣ getStyle This snippet can be used to get the value of a CSS rule for a particular element.
1const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];23getStyle(document.querySelector('p'), 'font-size'); // '16px'
4️⃣7️⃣ getType This snippet can be used to get the type of a value.
1const getType = v =>2v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();34getType(new Set([1, 2, 3])); // 'set'
4️⃣8️⃣ hasClass This snippet checks whether an element has a particular class.
1const hasClass = (el, className) => el.classList.contains(className);2hasClass(document.querySelector('p.special'), 'special'); // true
4️⃣9️⃣ head This snippet returns the head of a list.
1const head = arr => arr[0];23head([1, 2, 3]); // 1
5️⃣0️⃣ hide This snippet can be used to hide all elements specified.
1const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));23hide(document.querySelectorAll('img')); // Hides all <img> elements on the page
This post was inspired by one of my Twitter threads. Do follow me on Twitter to never miss out on tech content.