Skip to content

JavaScript snippets

536 short, self-contained JavaScript functions. Grouped by category below.

Arrays

Snippet Snippet Snippet
accumulate aperture arrayToCSV
arrayToHTMLList bifurcate bifurcateBy
castArray chunk chunkIntoN
chunkify compact countBy
countOccurrences difference differenceBy
differenceWith drop dropRight
dropRightWhile dropWhile everyNth
filterNonUnique filterNonUniqueBy filterUnique
filterUniqueBy findFirstN findLast
findLastIndex findLastN flatten
forEachRight frequencies groupBy
hasDuplicates haveSameContents head
includesAll includesAny indexBy
indexOfAll initial initialize2DArray
initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues
initializeNDArray insertAt intersection
intersectionBy intersectionWith isSorted
join last longestItem
mapConsecutive maxBy maxN
median minBy minN
mostFrequent none nthElement
objectFromPairs offset orderBy
orderWith partition partitionBy
percentile permutations pluck
pull pullAtIndex pullAtValue
pullBy reducedFilter reduceSuccessive
reduceWhich reject remove
sample sampleSize shank
shuffle similarity sortedIndex
sortedIndexBy sortedLastIndex sortedLastIndexBy
stableSort subSet sum
sumBy sumN superSet
symmetricDifference symmetricDifferenceBy symmetricDifferenceWith
tail take takeRight
takeRightUntil takeRightWhile takeUntil
takeWhile union unionBy
unionWith uniqueElements uniqueElementsBy
uniqueElementsByRight uniqueSymmetricDifference unzip
unzipWith without xProd
zip zipObject zipWith

Objects

Snippet Snippet Snippet
compactObject deepClone deepFreeze
deepGet deepMapKeys deepMerge
defaults dig equals
findKey findKeys findLastKey
flattenObject forOwn forOwnRight
get hasKey hasMany
hasOne invertKeyValues isDeepFrozen
isDisjoint isObjectLike isPlainObject
lowercaseKeys mapKeys mapObject
mapValues matches matchesWith
merge nest objectToEntries
objectToPairs objectToQueryString omit
omitBy pick pickBy
renameKeys shallowClone symbolizeKeys
toPairs transform unflattenObject

Functions

Snippet Snippet Snippet
ary attempt binary
bind bindAll bindKey
call chainAsync collectInto
compose composeRight complement
converge curry debounce
debouncePromise defer either
flip functionName functions
generateItems generatorToArray isAsyncFunction
isFunction isGeneratorFunction isPromiseLike
juxt memoize mostPerformant
negate nor not
nthArg once or
over overArgs partial
partialRight pipeAsyncFunctions pipeFunctions
promisify rearg runAsync
runPromisesInSeries sleep spreadOver
throttle timeTaken times
unary uncurry unfold
when xor

Strings

Snippet Snippet Snippet
byteSize caesarCipher capitalize
capitalizeEveryWord changeLightness compactWhitespace
containsWhitespace countSubstrings decapitalize
escapeHTML escapeRegExp expandTabs
extendHex fromCamelCase indentString
isAlpha isAlphaNumeric isAnagram
isIsomorphic isLowerCase isUpperCase
isValidJSON luhnCheck mask
normalizeLineEndings pad padNumber
palindrome parseCookie pluralize
prefix prettyBytes removeAccents
removeNonASCII removeWhitespace replaceLast
reverseString serializeCookie slugify
sortCharactersInString splitLines stringifyCircularJSON
stringPermutations stripHTMLTags swapCase
toCamelCase toKebabCase toSnakeCase
toTitleCase truncateString truncateStringAtWhitespace
unescapeHTML URLJoin words
wordWrap

Math & Numbers

Snippet Snippet Snippet
approximatelyEqual arithmeticProgression average
averageBy binomialCoefficient cartesianProduct
celsiusToFahrenheit clampNumber copySign
distance divmod euclideanDistance
factorial fahrenheitToCelsius fibonacci
frozenSet gcd geometricProgression
hammingDistance heapsort hz
inRange isPowerOfTen isPowerOfTwo
isPrime kMeans kmToMiles
kNearestNeighbors lcm levenshteinDistance
linearSearch logBase mapNumRange
maxDate mergeSortedArrays midpoint
milesToKm minDate nthRoot
powerset primeFactors primes
prod radsToDegrees randomAlphaNumeric
randomBoolean randomHexColorCode randomIntArrayInRange
randomIntegerInRange randomNumberInRange round
sdbm standardDeviation sumPower
toDecimalMark toOrdinalSuffix toRomanNumeral
toSafeInteger validateNumber vectorAngle
vectorDistance weightedAverage weightedSample

Date & Time

Snippet Snippet Snippet
addDaysToDate addMinutesToDate addWeekDays
countWeekDaysBetween dateRangeGenerator dayName
dayOfYear daysAgo daysFromNow
daysInMonth formatDuration formatSeconds
fromTimestamp getColonTimeFromDate getDaysDiffBetweenDates
getHoursDiffBetweenDates getMeridiemSuffixOfInteger getMinutesDiffBetweenDates
getMonthsDiffBetweenDates getSecondsDiffBetweenDates getTimestamp
isAfterDate isBeforeDate isBetweenDates
isDateValid isISOString isLeapYear
isSameDate isWeekday isWeekend
lastDateOfMonth quarterOfYear toISOStringWithTimezone
tomorrow weekOfYear yesterday

Browser & DOM

Snippet Snippet Snippet
addClass addEventListenerAll addMultipleEvents
addStyles atob both
bottomVisible btoa colorize
copyToClipboard counter createDirIfNotExists
createElement createEventHub currentURL
cycleGenerator detectDeviceType detectLanguage
elementContains elementIsFocused elementIsVisibleInViewport
fullscreen getAncestors getBaseURL
getElementsBiggerThanViewport getImages getParentsUntil
getProtocol getScrollPosition getSelectedText
getSiblings getStyle getURLParameters
getVerticalOffset hasClass hasFlags
hide httpDelete httpGet
httpPost httpPut httpsRedirect
injectCSS insertAfter insertBefore
isBrowser isBrowserTabFocused isLocalStorageEnabled
isNode isSameOrigin isSessionStorageEnabled
isTravisCI JSONtoCSV JSONToFile
listenOnce nodeListToArray observeMutations
off on onClickOutside
onScrollStop onUserInputChange queryStringToObject
readFileLines recordAnimationFrames redirect
removeElement removeEventListenerAll removeClass
renderElement requireUncached scrollToTop
serializeForm setStyle show
smoothScroll supportsTouchEvents toHash
toggleClass triggerEvent UUIDGeneratorBrowser
UUIDGeneratorNode walkThrough

Types & Checks

Snippet Snippet Snippet
assertValidKeys cloneRegExp coalesce
coalesceFactory combine CSVToArray
CSVToJSON formToObject getType
hashBrowser hashNode HSBToRGB
HSLToRGB is isAbsoluteURL
isArrayLike isBoolean isDuplexStream
isEmpty isNegativeZero isNil
isNull isNumber isObject
isPrimitive isReadableStream isStream
isString isSymbol isUndefined
isWritableStream RGBToHex RGBToHSB
RGBToHSL size toCurrency
toCharArray toHSLArray toHSLObject
toRGBArray toRGBObject truthCheckCollection
untildify yesNo

Sorting algorithms

Snippet Description
bubbleSort O(n²) comparison sort
bucketSort Distribution sort
heapsort O(n log n) in-place sort
insertionSort O(n²), efficient for small inputs
mergeSort O(n log n) divide-and-conquer sort
quickSort O(n log n) average, in-place
selectionSort O(n²) selection sort
binarySearch O(log n) search on sorted arrays