30 seconds of code
Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
- Use Ctrl + F or command + F to search for a snippet.
- Contributions welcome, please read the contribution guide.
- Snippets are written in ES6, use the Babel transpiler to ensure backwards-compatibility.
- You can import these snippets into VSCode, by following the instructions found here.
- You can search, view and copy these snippets from a terminal, using the CLI application from this repo.
- If you want to follow 30-seconds-of-code on social media, you can find us on Facebook, Instagram and Twitter.
Related projects
- 30 Seconds of CSS
- 30 Seconds of Interviews
- 30 Seconds of React
- 30 Seconds of Python (unofficial)
- 30 Seconds of PHP (unofficial)
Package
⚠️ NOTICE: A few of our snippets are not yet optimized for production (see disclaimers for individual snippet issues).
You can find a package with all the snippets on npm.
# With npm npm install 30-seconds-of-code # With yarn yarn add 30-seconds-of-code
Details
Browser
Node
// CommonJSconst _30s = ;_30s; // ES Modules;_30s;
Contents
🔌 Adapter
View contents
📚 Array
View contents
all
allEqual
any
arrayToCSV
bifurcate
bifurcateBy
chunk
compact
countBy
countOccurrences
deepFlatten
difference
differenceBy
differenceWith
drop
dropRight
dropRightWhile
dropWhile
everyNth
filterNonUnique
filterNonUniqueBy
findLast
findLastIndex
flatten
forEachRight
groupBy
head
indexOfAll
initial
initialize2DArray
initializeArrayWithRange
initializeArrayWithRangeRight
initializeArrayWithValues
initializeNDArray
intersection
intersectionBy
intersectionWith
isSorted
join
JSONtoCSV
last
longestItem
mapObject
maxN
minN
none
nthElement
offset
partition
permutations
pull
pullAtIndex
pullAtValue
pullBy
reducedFilter
reduceSuccessive
reduceWhich
reject
remove
sample
sampleSize
shank
shuffle
similarity
sortedIndex
sortedIndexBy
sortedLastIndex
sortedLastIndexBy
stableSort
symmetricDifference
symmetricDifferenceBy
symmetricDifferenceWith
tail
take
takeRight
takeRightWhile
takeWhile
toHash
union
unionBy
unionWith
uniqueElements
uniqueElementsBy
uniqueElementsByRight
uniqueSymmetricDifference
unzip
unzipWith
without
xProd
zip
zipObject
zipWith
🌐 Browser
View contents
arrayToHtmlList
bottomVisible
copyToClipboard
counter
createElement
createEventHub
currentURL
detectDeviceType
elementContains
elementIsVisibleInViewport
getImages
getScrollPosition
getStyle
hasClass
hashBrowser
hide
httpsRedirect
insertAfter
insertBefore
isBrowserTabFocused
nodeListToArray
observeMutations
off
on
onUserInputChange
prefix
recordAnimationFrames
redirect
runAsync
scrollToTop
setStyle
show
smoothScroll
toggleClass
triggerEvent
UUIDGeneratorBrowser
⏱️ Date
View contents
🎛️ Function
View contents
➗ Math
View contents
approximatelyEqual
average
averageBy
binomialCoefficient
clampNumber
degreesToRads
digitize
distance
elo
factorial
fibonacci
gcd
geometricProgression
hammingDistance
inRange
isDivisible
isEven
isNegativeZero
isPrime
lcm
luhnCheck
maxBy
median
minBy
percentile
powerset
primes
radsToDegrees
randomIntArrayInRange
randomIntegerInRange
randomNumberInRange
round
sdbm
standardDeviation
sum
sumBy
sumPower
toSafeInteger
📦 Node
View contents
🗃️ Object
View contents
bindAll
deepClone
deepFreeze
defaults
dig
equals
findKey
findLastKey
flattenObject
forOwn
forOwnRight
functions
get
invertKeyValues
lowercaseKeys
mapKeys
mapValues
matches
matchesWith
merge
nest
objectFromPairs
objectToPairs
omit
omitBy
orderBy
pick
pickBy
renameKeys
shallowClone
size
transform
truthCheckCollection
unflattenObject
📜 String
View contents
byteSize
capitalize
capitalizeEveryWord
CSVToArray
CSVToJSON
decapitalize
escapeHTML
escapeRegExp
fromCamelCase
indentString
isAbsoluteURL
isAnagram
isLowerCase
isUpperCase
mapString
mask
pad
palindrome
pluralize
removeNonASCII
reverseString
sortCharactersInString
splitLines
stringPermutations
stripHTMLTags
toCamelCase
toKebabCase
toSnakeCase
toTitleCase
truncateString
unescapeHTML
URLJoin
words
📃 Type
View contents
🔧 Utility
View contents
🔌 Adapter
ary
Creates a function that accepts up to n
arguments, ignoring any additional arguments.
Call the provided function, fn
, with up to n
arguments, using Array.prototype.slice(0,n)
and the spread operator (...
).
const ary = ;
Examples
const firstTwoMax = ;2 6 'a' 8 4 6 10; // [6, 8, 10]
call
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
const call = contextkey...args;
Examples
Promise ; // [ 2, 4, 6 ]const map = call;Promise ; // [ 2, 4, 6 ]
collectInto
Changes a function that accepts an array into a variadic function.
Given a function, return a closure that collects all inputs into an array-accepting function.
const collectInto = ;
Examples
const Pall = ;let p1 = Promise;let p2 = Promise;let p3 = ;; // [1, 2, 3] (after about 2 seconds)
flip
Flip takes a function as an argument, then makes the first argument the last.
Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.
const flip = ;
Examples
let a = name: 'John Smith' ;let b = {};const mergeFrom = ;let mergePerson = mergeFrom;; // == bb = {};Object; // == b
over
Creates a function that invokes each provided function with the arguments it receives and returns the results.
Use Array.prototype.map()
and Function.prototype.apply()
to apply each function to the given arguments.
const over = fns;
Examples
const minMax = ;; // [1,5]
overArgs
Creates a function that invokes the provided function with its arguments transformed.
Use Array.prototype.map()
to apply transforms
to args
in combination with the spread operator (...
) to pass the transformed arguments to fn
.
const overArgs = ;
Examples
const square = n * n;const double = n * 2;const fn = ;; // [81, 6]
pipeAsyncFunctions
Performs left-to-right function composition for asynchronous functions.
Use Array.prototype.reduce()
with the spread operator (...
) to perform left-to-right function composition using Promise.then()
.
The functions can return a combination of: simple values, Promise
's, or they can be defined as async
ones returning through await
.
All functions must be unary.
const pipeAsyncFunctions = fns;
Examples
const sum = ;async console; // 15 (after one second);
pipeFunctions
Performs left-to-right function composition.
Use Array.prototype.reduce()
with the spread operator (...
) to perform left-to-right function composition.
The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
const pipeFunctions = fns;
Examples
const add5 = x + 5;const multiply = x * y;const multiplyAndAdd5 = ;; // 15
promisify
Converts an asynchronous function to return a promise.
Use currying to return a function returning a Promise
that calls the original function.
Use the ...rest
operator to pass in all the parameters.
In Node 8+, you can use util.promisify
const promisify = ;
Examples
const delay = ;; // // Promise resolves after 2s
rearg
Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.
Use Array.prototype.map()
to reorder arguments based on indexes
in combination with the spread operator (...
) to pass the transformed arguments to fn
.
const rearg = ;
Examples
var rearged = ;; // ['a', 'b', 'c']
spreadOver
Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.
Use closures and the spread operator (...
) to map the array of arguments to the inputs of the function.
const spreadOver = ;
Examples
const arrayMax = ;; // 3
unary
Creates a function that accepts up to one argument, ignoring any additional arguments.
Call the provided function, fn
, with just the first argument given.
const unary = ;
Examples
'6' '8' '10'; // [6, 8, 10]
📚 Array
all
Returns true
if the provided predicate function returns true
for all elements in a collection, false
otherwise.
Use Array.prototype.every()
to test if all elements in the collection return true
based on fn
.
Omit the second argument, fn
, to use Boolean
as a default.
const all = arr;
Examples
; // true; // true
allEqual
Check if all elements in an array are equal.
Use Array.prototype.every()
to check if all the elements of the array are the same as the first one.
const allEqual = arr;
Examples
; // false; // true
any
Returns true
if the provided predicate function returns true
for at least one element in a collection, false
otherwise.
Use Array.prototype.some()
to test if any elements in the collection return true
based on fn
.
Omit the second argument, fn
, to use Boolean
as a default.
const any = arr;
Examples
; // true; // true
arrayToCSV
Converts a 2D array to a comma-separated values (CSV) string.
Use Array.prototype.map()
and Array.prototype.join(delimiter)
to combine individual 1D arrays (rows) into strings.
Use Array.prototype.join('\n')
to combine all rows into a CSV string, separating each row with a newline.
Omit the second argument, delimiter
, to use a default delimiter of ,
.
const arrayToCSV = arr;
Examples
; // '"a","b"\n"c","d"'; // '"a";"b"\n"c";"d"'
bifurcate
Splits values into two groups. If an element in filter
is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
Use Array.prototype.reduce()
and Array.prototype.push()
to add elements to groups, based on filter
.
const bifurcate = arr;
Examples
; // [ ['beep', 'boop', 'bar'], ['foo'] ]
bifurcateBy
Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
Use Array.prototype.reduce()
and Array.prototype.push()
to add elements to groups, based on the value returned by fn
for each element.
const bifurcateBy = arr;
Examples
; // [ ['beep', 'boop', 'bar'], ['foo'] ]
chunk
Chunks an array into smaller arrays of a specified size.
Use Array.from()
to create a new array, that fits the number of chunks that will be produced.
Use Array.prototype.slice()
to map each element of the new array to a chunk the length of size
.
If the original array can't be split evenly, the final chunk will contain the remaining elements.
const chunk = Array;
Examples
; // [[1,2],[3,4],[5]]
compact
Removes falsey values from an array.
Use Array.prototype.filter()
to filter out falsey values (false
, null
, 0
, ""
, undefined
, and NaN
).
const compact = arr;
Examples
; // [ 1, 2, 3, 'a', 's', 34 ]
countBy
Groups the elements of an array based on the given function and returns the count of elements in each group.
Use Array.prototype.map()
to map the values of an array to a function or property name.
Use Array.prototype.reduce()
to create an object, where the keys are produced from the mapped results.
const countBy = arr;
Examples
; // {4: 1, 6: 2}; // {3: 2, 5: 1}
countOccurrences
Counts the occurrences of a value in an array.
Use Array.prototype.reduce()
to increment a counter each time you encounter the specific value inside the array.
const countOccurrences = arr;
Examples
; // 3
deepFlatten
Deep flattens an array.
Use recursion.
Use Array.prototype.concat()
with an empty array ([]
) and the spread operator (...
) to flatten an array.
Recursively flatten each element that is an array.
const deepFlatten = ;
Examples
; // [1,2,3,4,5]
difference
Returns the difference between two arrays.
Create a Set
from b
, then use Array.prototype.filter()
on a
to only keep values not contained in b
.
const difference = { const s = b; return a;};
Examples
; // [3]
differenceBy
Returns the difference between two arrays, after applying the provided function to each array element of both.
Create a Set
by applying fn
to each element in b
, then use Array.prototype.filter()
in combination with fn
on a
to only keep values not contained in the previously created set.
const differenceBy = { const s = b; return a;};
Examples
; // [1.2]; // [ { x: 2 } ]
differenceWith
Filters out all values from an array for which the comparator function does not return true
.
Use Array.prototype.filter()
and Array.prototype.findIndex()
to find the appropriate values.
const differenceWith = arr;
Examples
; // [1, 1.2]
drop
Returns a new array with n
elements removed from the left.
Use Array.prototype.slice()
to slice the remove the specified number of elements from the left.
const drop = arr;
Examples
; // [2,3]; // [3]; // []
dropRight
Returns a new array with n
elements removed from the right.
Use Array.prototype.slice()
to slice the remove the specified number of elements from the right.
const dropRight = arr;
Examples
; // [1,2]; // [1]; // []
dropRightWhile
Removes elements from the end of an array until the passed function returns true
. Returns the remaining elements in the array.
Loop through the array, using Array.prototype.slice()
to drop the last element of the array until the returned value from the function is true
.
Returns the remaining elements.
const dropRightWhile = { while arrlength > 0 && ! arr = arr; return arr;};
Examples
; // [1, 2]
dropWhile
Removes elements in an array until the passed function returns true
. Returns the remaining elements in the array.
Loop through the array, using Array.prototype.slice()
to drop the first element of the array until the returned value from the function is true
.
Returns the remaining elements.
const dropWhile = { while arrlength > 0 && ! arr = arr; return arr;};
Examples
; // [3,4]
everyNth
Returns every nth element in an array.
Use Array.prototype.filter()
to create a new array that contains every nth element of a given array.
const everyNth = arr;
Examples
; // [ 2, 4, 6 ]
filterNonUnique
Filters out the non-unique values in an array.
Use Array.prototype.filter()
for an array containing only the unique values.
const filterNonUnique = arr;
Examples
; // [1, 3, 5]
filterNonUniqueBy
Filters out the non-unique values in an array, based on a provided comparator function.
Use Array.prototype.filter()
and Array.prototype.every()
for an array containing only the unique values, based on the comparator function, fn
.
The comparator function takes four arguments: the values of the two elements being compared and their indexes.
const filterNonUniqueBy = arr;
Examples
; // [ { id: 2, value: 'c' } ]
findLast
Returns the last element for which the provided function returns a truthy value.
Use Array.prototype.filter()
to remove elements for which fn
returns falsey values, Array.prototype.pop()
to get the last one.
const findLast = arr;
Examples
; // 3
findLastIndex
Returns the index of the last element for which the provided function returns a truthy value.
Use Array.prototype.map()
to map each element to an array with its index and value.
Use Array.prototype.filter()
to remove elements for which fn
returns falsey values, Array.prototype.pop()
to get the last one.
const findLastIndex = arr 0;
Examples
; // 2 (index of the value 3)
flatten
Flattens an array up to the specified depth.
Use recursion, decrementing depth
by 1 for each level of depth.
Use Array.prototype.reduce()
and Array.prototype.concat()
to merge elements or arrays.
Base case, for depth
equal to 1
stops recursion.
Omit the second argument, depth
to flatten only to a depth of 1
(single flatten).
const flatten = arr;
Examples
; // [1, 2, 3, 4]; // [1, 2, 3, [4, 5], 6, 7, 8]
forEachRight
Executes a provided function once for each array element, starting from the array's last element.
Use Array.prototype.slice(0)
to clone the given array, Array.prototype.reverse()
to reverse it and Array.prototype.forEach()
to iterate over the reversed array.
const forEachRight = arr ;
Examples
; // '4', '3', '2', '1'
groupBy
Groups the elements of an array based on the given function.
Use Array.prototype.map()
to map the values of an array to a function or property name.
Use Array.prototype.reduce()
to create an object, where the keys are produced from the mapped results.
const groupBy = arr;
Examples
; // {4: [4.2], 6: [6.1, 6.3]}; // {3: ['one', 'two'], 5: ['three']}
head
Returns the head of a list.
Use arr[0]
to return the first element of the passed array.
const head = arr0;
Examples
; // 1
indexOfAll
Returns all indices of val
in an array.
If val
never occurs, returns []
.
Use Array.prototype.reduce()
to loop over elements and store indices for matching elements.
Return the array of indices.
const indexOfAll = arr;
Examples
; // [0,3]; // []
initial
Returns all the elements of an array except the last one.
Use arr.slice(0,-1)
to return all but the last element of the array.
const initial = arr;
Examples
; // [1,2]
initialize2DArray
Initializes a 2D array of given width and height and value.
Use Array.prototype.map()
to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to null
.
const initialize2DArray = Array;
Examples
; // [[0,0], [0,0]]
initializeArrayWithRange
Initializes an array containing the numbers in the specified range where start
and end
are inclusive with their common difference step
.
Use Array.from()
to create an array of the desired length, (end - start + 1)/step
, and a map function to fill it with the desired values in the given range.
You can omit start
to use a default value of 0
.
You can omit step
to use a default value of 1
.
const initializeArrayWithRange = Array;
Examples
; // [0,1,2,3,4,5]; // [3,4,5,6,7]; // [0,2,4,6,8]
initializeArrayWithRangeRight
Initializes an array containing the numbers in the specified range (in reverse) where start
and end
are inclusive with their common difference step
.
Use Array.from(Math.ceil((end+1-start)/step))
to create an array of the desired length(the amounts of elements is equal to (end-start)/step
or (end+1-start)/step
for inclusive end), Array.prototype.map()
to fill with the desired values in a range.
You can omit start
to use a default value of 0
.
You can omit step
to use a default value of 1
.
const initializeArrayWithRangeRight = Array;
Examples
; // [5,4,3,2,1,0]; // [7,6,5,4,3]; // [8,6,4,2,0]
initializeArrayWithValues
Initializes and fills an array with the specified values.
Use Array(n)
to create an array of the desired length, fill(v)
to fill it with the desired values.
You can omit val
to use a default value of 0
.
const initializeArrayWithValues = Arrayn;
Examples
; // [2, 2, 2, 2, 2]
initializeNDArray
Create a n-dimensional array with given value.
Use recursion.
Use Array.prototype.map()
to generate rows where each is a new array initialized using initializeNDArray
.
const initializeNDArray = argslength === 0 ? val : Array;
Examples
; // [1,1,1]; // [[[5,5],[5,5]],[[5,5],[5,5]]]
intersection
Returns a list of elements that exist in both arrays.
Create a Set
from b
, then use Array.prototype.filter()
on a
to only keep values contained in b
.
const intersection = { const s = b; return a;};
Examples
; // [2, 3]
intersectionBy
Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.
Create a Set
by applying fn
to all elements in b
, then use Array.prototype.filter()
on a
to only keep elements, which produce values contained in b
when fn
is applied to them.
const intersectionBy = { const s = b; return a;};
Examples
; // [2.1]
intersectionWith
Returns a list of elements that exist in both arrays, using a provided comparator function.
Use Array.prototype.filter()
and Array.prototype.findIndex()
in combination with the provided comparator to determine intersecting values.
const intersectionWith = a;
Examples
; // [1.5, 3, 0]
isSorted
Returns 1
if the array is sorted in ascending order, -1
if it is sorted in descending order or 0
if it is not sorted.
Calculate the ordering direction
for the first two elements.
Use Object.entries()
to loop over array objects and compare them in pairs.
Return 0
if the direction
changes or the direction
if the last element is reached.
const isSorted = { let direction = -arr0 - arr1; for let i val of arr direction = !direction ? -arri - 1 - arri : direction; if i === arrlength - 1 return !direction ? 0 : direction; else if val - arri + 1 * direction > 0 return 0; };
Examples
; // 1; // -1; // 0
join
Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.
Use Array.prototype.reduce()
to combine elements into a string.
Omit the second argument, separator
, to use a default separator of ','
.
Omit the third argument, end
, to use the same value as separator
by default.
const join = arr;
Examples
; // "pen,pineapple,apple&pen"; // "pen,pineapple,apple,pen"; // "pen,pineapple,apple,pen"
Converts an array of objects to a comma-separated values (CSV) string that contains only the columns
specified.
Use Array.prototype.join(delimiter)
to combine all the names in columns
to create the first row.
Use Array.prototype.map()
and Array.prototype.reduce()
to create a row for each object, substituting non-existent values with empty strings and only mapping values in columns
.
Use Array.prototype.join('\n')
to combine all rows into a string.
Omit the third argument, delimiter
, to use a default delimiter of ,
.
const JSONtoCSV = columns ...arr ;
Examples
; // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"'; // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"'
last
Returns the last element in an array.
Use arr.length - 1
to compute the index of the last element of the given array and returning it.
const last = arrarrlength - 1;
Examples
; // 3
longestItem
Takes any number of iterable objects or objects with a length
property and returns the longest one.
If multiple objects have the same length, the first one will be returned.
Returns undefined
if no arguments are provided.
Use Array.prototype.reduce()
, comparing the length
of objects to find the longest one.
const longestItem = vals;
Examples
; // 'testcase'; // 'abc'; // 'abcd'; // [1, 2, 3, 4, 5]; // 'foobar'
Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new Array
to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
const mapObject = a = arr arr a0 ;
Examples
const squareIt = ;; // { 1: 1, 2: 4, 3: 9 }
maxN
Returns the n
maximum elements from the provided array.
If n
is greater than or equal to the provided array's length, then return the original array (sorted in descending order).
Use Array.prototype.sort()
combined with the spread operator (...
) to create a shallow clone of the array and sort it in descending order.
Use Array.prototype.slice()
to get the specified number of elements.
Omit the second argument, n
, to get a one-element array.
const maxN = ...arr;
Examples
; // [3]; // [3,2]
minN
Returns the n
minimum elements from the provided array.
If n
is greater than or equal to the provided array's length, then return the original array (sorted in ascending order).
Use Array.prototype.sort()
combined with the spread operator (...
) to create a shallow clone of the array and sort it in ascending order.
Use Array.prototype.slice()
to get the specified number of elements.
Omit the second argument, n
, to get a one-element array.
const minN = ...arr;
Examples
; // [1]; // [1,2]
none
Returns true
if the provided predicate function returns false
for all elements in a collection, false
otherwise.
Use Array.prototype.some()
to test if any elements in the collection return true
based on fn
.
Omit the second argument, fn
, to use Boolean
as a default.
const none = !arr;
Examples
; // true; // true
nthElement
Returns the nth element of an array.
Use Array.prototype.slice()
to get an array containing the nth element at the first place.
If the index is out of bounds, return undefined
.
Omit the second argument, n
, to get the first element of the array.
const nthElement = n === -1 ? arr : arr0;
Examples
; // 'b'; // 'a'
offset
Moves the specified amount of elements to the end of the array.
Use Array.prototype.slice()
twice to get the elements after the specified index and the elements before that.
Use the spread operator(...
) to combine the two into one array.
If offset
is negative, the elements will be moved from end to start.
const offset = ...arr ...arr;
Examples
; // [3, 4, 5, 1, 2]; // [4, 5, 1, 2, 3]
partition
Groups the elements into two arrays, depending on the provided function's truthiness for each element.
Use Array.prototype.reduce()
to create an array of two arrays.
Use Array.prototype.push()
to add elements for which fn
returns true
to the first array and elements for which fn
returns false
to the second one.
const partition = arr;
Examples
const users = user: 'barney' age: 36 active: false user: 'fred' age: 40 active: true ;; // [[{ 'user': 'fred', 'age': 40, 'active': true }],[{ 'user': 'barney', 'age': 36, 'active': false }]]
⚠️ WARNING: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations.
Generates all permutations of an array's elements (contains duplicates).
Use recursion.
For each element in the given array, create all the partial permutations for the rest of its elements.
Use Array.prototype.map()
to combine the element with each partial permutation, then Array.prototype.reduce()
to combine all permutations in one array.
Base cases are for array length
equal to 2
or 1
.
const permutations = { if arrlength <= 2 return arrlength === 2 ? arr arr1 arr0 : arr; return arr;};
Examples
; // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]
pull
Mutates the original array to filter out the values specified.
Use Array.prototype.filter()
and Array.prototype.includes()
to pull out the values that are not needed.
Use Array.prototype.length = 0
to mutate the passed in an array by resetting it's length to zero and Array.prototype.push()
to re-populate it with only the pulled values.
(For a snippet that does not mutate the original array see without
)
const pull = { let argState = Array ? args0 : args; let pulled = arr; arrlength = 0; pulled;};
Examples
let myArray = 'a' 'b' 'c' 'a' 'b' 'c';; // myArray = [ 'b', 'b' ]
Mutates the original array to filter out the values at the specified indexes.
Use Array.prototype.filter()
and Array.prototype.includes()
to pull out the values that are not needed.
Use Array.prototype.length = 0
to mutate the passed in an array by resetting it's length to zero and Array.prototype.push()
to re-populate it with only the pulled values.
Use Array.prototype.push()
to keep track of pulled values
const pullAtIndex = { let removed = ; let pulled = arr ; arrlength = 0; pulled; return removed;};
Examples
let myArray = 'a' 'b' 'c' 'd';let pulled = ; // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
Mutates the original array to filter out the values specified. Returns the removed elements.
Use Array.prototype.filter()
and Array.prototype.includes()
to pull out the values that are not needed.
Use Array.prototype.length = 0
to mutate the passed in an array by resetting it's length to zero and Array.prototype.push()
to re-populate it with only the pulled values.
Use Array.prototype.push()
to keep track of pulled values
const pullAtValue = { let removed = pushToRemove = arr mutateTo = arr; arrlength = 0; mutateTo; return removed;};
Examples
let myArray = 'a' 'b' 'c' 'd';let pulled = ; // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
Mutates the original array to filter out the values specified, based on a given iterator function.
Check if the last argument provided in a function.
Use Array.prototype.map()
to apply the iterator function fn
to all array elements.
Use Array.prototype.filter()
and Array.prototype.includes()
to pull out the values that are not needed.
Use Array.prototype.length = 0
to mutate the passed in an array by resetting it's length to zero and Array.prototype.push()
to re-populate it with only the pulled values.
const pullBy = { const length = argslength; let fn = length > 1 ? argslength - 1 : undefined; fn = typeof fn == 'function' ? args fn : undefined; let argState = Array ? args0 : args; let pulled = arr; arrlength = 0; pulled;};
Examples
var myArray = x: 1 x: 2 x: 3 x: 1 ;; // myArray = [{ x: 2 }]
reducedFilter
Filter an array of objects based on a condition while also filtering out unspecified keys.
Use Array.prototype.filter()
to filter the array based on the predicate fn
so that it returns the objects for which the condition returned a truthy value.
On the filtered array, use Array.prototype.map()
to return the new object using Array.prototype.reduce()
to filter out the keys which were not supplied as the keys
argument.
const reducedFilter = data;
Examples
const data = id: 1 name: 'john' age: 24 id: 2 name: 'mike' age: 50 ; ; // [{ id: 2, name: 'mike'}]
reduceSuccessive
Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values.
Use Array.prototype.reduce()
to apply the given function to the given array, storing each new result.
const reduceSuccessive = arr;
Examples
; // [0, 1, 3, 6, 10, 15, 21]
reduceWhich
Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.
Use Array.prototype.reduce()
in combination with the comparator
function to get the appropriate element in the array.
You can omit the second parameter, comparator
, to use the default one that returns the minimum element in the array.
const reduceWhich = arr a - b arr;
Examples
; // 1; // 3; // {name: "Lucy", age: 9}
reject
Takes a predicate and array, like Array.prototype.filter()
, but only keeps x
if pred(x) === false
.
const reject = array;
Examples
; // [1, 3, 5]; // ['Pear', 'Kiwi']
remove
Removes elements from an array for which the given function returns false
.
Use Array.prototype.filter()
to find array elements that return truthy values and Array.prototype.reduce()
to remove elements using Array.prototype.splice()
.
The func
is invoked with three arguments (value, index, array
).
const remove = Array ? arr : ;
Examples
; // [2, 4]
sample
Returns a random element from an array.
Use Math.random()
to generate a random number, multiply it by length
and round it off to the nearest whole number using Math.floor()
.
This method also works with strings.
const sample = arrMath;
Examples
; // 9
sampleSize
Gets n
random elements at unique keys from array
up to the size of array
.
Shuffle the array using the Fisher-Yates algorithm.
Use Array.prototype.slice()
to get the first n
elements.
Omit the second argument, n
to get only one element at random from the array.
const sampleSize = { let m = arrlength; while m const i = Math; arrm arri = arri arrm; return arr;};
Examples
; // [3,1]; // [2,3,1]
shank
Has the same functionality as Array.prototype.splice()
, but returning a new array instead of mutating the original array.
Use Array.prototype.slice()
and Array.prototype.concat()
to get a new array with the new contents after removing existing elements and/or adding new elements.
Omit the second argument, index
, to start at 0
.
Omit the third argument, delCount
, to remove 0
elements.
Omit the fourth argument, elements
, in order to not add any new elements.
const shank = arr ;
Examples
const names = 'alpha' 'bravo' 'charlie';const namesAndDelta = ; // [ 'alpha', 'delta', 'bravo', 'charlie' ]const namesNoBravo = ; // [ 'alpha', 'charlie' ]console; // ['alpha', 'bravo', 'charlie']
shuffle
Randomizes the order of the values of an array, returning a new array.
Uses the Fisher-Yates algorithm to reorder the elements of the array.
const shuffle = { let m = arrlength; while m const i = Math; arrm arri = arri arrm; return arr;};
Examples
const foo = 1 2 3;; // [2, 3, 1], foo = [1, 2, 3]
similarity
Returns an array of elements that appear in both arrays.
Use Array.prototype.filter()
to remove values that are not part of values
, determined using Array.prototype.includes()
.
const similarity = arr;
Examples
; // [1, 2]
sortedIndex
Returns the lowest index at which value should be inserted into array in order to maintain its sort order.
Check if the array is sorted in descending order (loosely).
Use Array.prototype.findIndex()
to find the appropriate index where the element should be inserted.
const sortedIndex = { const isDescending = arr0 > arrarrlength - 1; const index = arr; return index === -1 ? arrlength : index;};
Examples
; // 1; // 1
sortedIndexBy
Returns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.
Check if the array is sorted in descending order (loosely).
Use Array.prototype.findIndex()
to find the appropriate index where the element should be inserted, based on the iterator function fn
.
const sortedIndexBy = { const isDescending = > ; const val = ; const index = arr; return index === -1 ? arrlength : index;};
Examples
; // 0
sortedLastIndex
Returns the highest index at which value should be inserted into array in order to maintain its sort order.
Check if the array is sorted in descending order (loosely).
Use Array.prototype.reverse()
and Array.prototype.findIndex()
to find the appropriate last index where the element should be inserted.
const sortedLastIndex = { const isDescending = arr0 > arrarrlength - 1; const index = arr; return index === -1 ? 0 : arrlength - index;};
Examples
; // 4
sortedLastIndexBy
Returns the highest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.
Check if the array is sorted in descending order (loosely).
Use Array.prototype.map()
to apply the iterator function to all elements of the array.
Use Array.prototype.reverse()
and Array.prototype.findIndex()
to find the appropriate last index where the element should be inserted, based on the provided iterator function.
const sortedLastIndexBy = { const isDescending = > ; const val = ; const index = arr ; return index === -1 ? 0 : arrlength - index;};
Examples
; // 1
Performs stable sorting of an array, preserving the initial indexes of items when their values are the same. Does not mutate the original array, but returns a new array instead.
Use Array.prototype.map()
to pair each element of the input array with its corresponding index.
Use Array.prototype.sort()
and a compare
function to sort the list, preserving their initial order if the items compared are equal.
Use Array.prototype.map()
to convert back to the initial array items.
const stableSort = arr ;
Examples
const arr = 0 1 2 3 4 5 6 7 8 9 10;const stable = ; // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
symmetricDifference
Returns the symmetric difference between two arrays, without filtering out duplicate values.
Create a Set
from each array, then use Array.prototype.filter()
on each of them to only keep values not contained in the other.
const symmetricDifference = { const sA = a sB = b; return ...a ...b;};
Examples
; // [3, 4]; // [2, 2, 3]
symmetricDifferenceBy
Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.
Create a Set
by applying fn
to each array's elements, then use Array.prototype.filter()
on each of them to only keep values not contained in the other.
const symmetricDifferenceBy = { const sA = a sB = b; return ...a ...b;};
Examples
; // [ 1.2, 3.4 ]
symmetricDifferenceWith
Returns the symmetric difference between two arrays, using a provided function as a comparator.
Use Array.prototype.filter()
and Array.prototype.findIndex()
to find the appropriate values.
const symmetricDifferenceWith = ...arr ...val;
Examples
; // [1, 1.2, 3.9]
tail
Returns all elements in an array except for the first one.
Return Array.prototype.slice(1)
if the array's length
is more than 1
, otherwise, return the whole array.
const tail = arrlength > 1 ? arr : arr;
Examples
; // [2,3]; // [1]
take
Returns an array with n elements removed from the beginning.
Use Array.prototype.slice()
to create a slice of the array with n
elements taken from the beginning.
const take = arr;
Examples
; // [1, 2, 3]; // []
takeRight
Returns an array with n elements removed from the end.
Use Array.prototype.slice()
to create a slice of the array with n
elements taken from the end.
const takeRight = arr;
Examples
; // [ 2, 3 ]; // [3]
takeRightWhile
Removes elements from the end of an array until the passed function returns true
. Returns the removed elements.
Loop through the array, using a Array.prototype.reduceRight()
and accumulating elements while the function returns falsy value.
const takeRightWhile = arr;
Examples
; // [3, 4]
takeWhile
Removes elements in an array until the passed function returns true
. Returns the removed elements.
Loop through the array, using a for...of
loop over Array.prototype.entries()
until the returned value from the function is true
.
Return the removed elements, using Array.prototype.slice()
.
const takeWhile = { for const i val of arr if return arr; return arr;};
Examples
; // [1, 2]
toHash
Reduces a given Array-like into a value hash (keyed data store).
Given an Iterable or Array-like structure, call Array.prototype.reduce.call()
on the provided object to step over it and return an Object, keyed by the reference value.
const toHash = Arrayprototypereduce;
Examples
; // { 0: 4, 1: 3, 2: 2, 3: 1 }; // { label: { a: 'label' } }// A more in depth example:let users = id: 1 first: 'Jon' id: 2 first: 'Joe' id: 3 first: 'Moe' ;let managers = manager: 1 employees: 2 3 ;// We use function here because we want a bindable reference, but a closure referencing the hash would work, too.managers;managers; // [ { manager:1, employees: [ { id: 2, first: "Joe" }, { id: 3, first: "Moe" } ] } ]
union
Returns every element that exists in any of the two arrays once.
Create a Set
with all values of a
and b
and convert to an array.
const union = Array;
Examples
; // [1,2,3,4]
unionBy
Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both.
Create a Set
by applying all fn
to all values of a
.
Create a Set
from a
and all elements in b
whose value, after applying fn
does not match a value in the previously created set.
Return the last set converted to an array.
const unionBy = { const s = a; return Array;};
Examples
; // [2.1, 1.2]
unionWith
Returns every element that exists in any of the two arrays once, using a provided comparator function.
Create a Set
with all values of a
and values in b
for which the comparator finds no matches in a
, using Array.prototype.findIndex()
.
const unionWith = Array;
Examples
; // [1, 1.2, 1.5, 3, 0, 3.9]
uniqueElements
Returns all unique values of an array.
Use ES6 Set
and the ...rest
operator to discard all duplicated values.
const uniqueElements = ...arr;
Examples
; // [1, 2, 3, 4, 5]
uniqueElementsBy
Returns all unique values of an array, based on a provided comparator function.
Use Array.prototype.reduce()
and Array.prototype.some()
for an array containing only the first unique occurence of each value, based on the comparator function, fn
.
The comparator function takes two arguments: the values of the two elements being compared.
const uniqueElementsBy = arr;
Examples
; // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ]
uniqueElementsByRight
Returns all unique values of an array, based on a provided comparator function.
Use Array.prototype.reduce()
and Array.prototype.some()
for an array containing only the last unique occurence of each value, based on the comparator function, fn
.
The comparator function takes two arguments: the values of the two elements being compared.
const uniqueElementsByRight = arr;
Examples
; // [ { id: 0, value: 'e' }, { id: 1, value: 'd' }, { id: 2, value: 'c' } ]
uniqueSymmetricDifference
Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.
Use Array.prototype.filter()
and Array.prototype.includes()
on each array to remove values contained in the other, then create a Set
from the results, removing duplicate values.
const uniqueSymmetricDifference = ......a ...b;
Examples
; // [3, 4]; // [2, 3]
unzip
Creates an array of arrays, ungrouping the elements in an array produced by zip.
Use Math.max.apply()
to get the longest subarray in the array, Array.prototype.map()
to make each element an array.
Use Array.prototype.reduce()
and Array.prototype.forEach()
to map grouped values to individual arrays.
const unzip = arr;
Examples
; // [['a', 'b'], [1, 2], [true, false]]; // [['a', 'b'], [1, 2], [true]]
Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.
Use Math.max.apply()
to get the longest subarray in the array, Array.prototype.map()
to make each element an array.
Use Array.prototype.reduce()
and Array.prototype.forEach()
to map grouped values to individual arrays.
Use Array.prototype.map()
and the spread operator (...
) to apply fn
to each individual group of elements.
const unzipWith = arr ;
Examples
; // [3, 30, 300]
without
Filters out the elements of an array, that have one of the specified values.
Use Array.prototype.filter()
to create an array excluding(using !Array.includes()
) all given values.
(For a snippet that mutates the original array see pull
)
const without = arr;
Examples
; // [3]
xProd
Creates a new array out of the two supplied by creating each possible pair from the arrays.
Use Array.prototype.reduce()
, Array.prototype.map()
and Array.prototype.concat()
to produce every possible pair from the elements of the two arrays and save them in an array.
const xProd = a;
Examples
; // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
zip
Creates an array of elements, grouped based on the position in the original arrays.
Use Math.max.apply()
to get the longest array in the arguments.
Creates an array with that length as return value and use Array.from()
with a map-function to create an array of grouped elements.
If lengths of the argument-arrays vary, undefined
is used where no value could be found.
const zip = { const maxLength = Math; return Array;};
Examples
; // [['a', 1, true], ['b', 2, false]]; // [['a', 1, true], [undefined, 2, false]]
zipObject
Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.
Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using Array.prototype.reduce()
.
const zipObject = props;
Examples
; // {a: 1, b: 2, c: undefined}; // {a: 1, b: 2}
Creates an array of elements, grouped based on the position in the original arrays and using function as the last value to specify how grouped values should be combined.
Check if the last argument provided is a function.
Use Math.max()
to get the longest array in the arguments.
Creates an array with that length as return value and use Array.from()
with a map-function to create an array of grouped elements.
If lengths of the argument-arrays vary, undefined
is used where no value could be found.
The function is invoked with the elements of each group (...group)
.
const zipWith = { const fn = typeof arrayarraylength - 1 === 'function' ? array : undefined; return Array;};
Examples
; // [111,222]; // [111, 222, '3bc']
🌐 Browser
arrayToHtmlList
Converts the given array elements into <li>
tags and appends them to the list of the given id.
Use Array.prototype.map()
, document.querySelector()
, and an anonymous inner closure to create a list of html tags.
const arrayToHtmlList = el = document elinnerHTML += arr ;
Examples
;
bottomVisible
Returns true
if the bottom of the page is visible, false
otherwise.
Use scrollY
, scrollHeight
and clientHeight
to determine if the bottom of the page is visible.
const bottomVisible = documentdocumentElementclientHeight + windowscrollY >= documentdocumentElementscrollHeight || documentdocumentElementclientHeight;
Examples
; // true
⚠️ NOTICE: The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it here.
Copy a string to the clipboard.
Only works as a result of user action (i.e. inside a click
event listener).
Create a new <textarea>
element, fill it with the supplied data and add it to the HTML document.
Use Selection.getRangeAt()
to store the selected range (if any).
Use document.execCommand('copy')
to copy to the clipboard.
Remove the <textarea>
element from the HTML document.
Finally, use Selection().addRange()
to recover the original selected range (if any).
const copyToClipboard = { const el = document; elvalue = str; el; elstyleposition = 'absolute'; elstyleleft = '-9999px'; documentbody; const selected = documentrangeCount > 0 ? document : false; el; document; documentbody; if selected document; document; };
Examples
; // 'Lorem ipsum' copied to clipboard.
Creates a counter with the specified range, step and duration for the specified selector.
Check if step
has the proper sign and change it accordingly.
Use setInterval()
in combination with Math.abs()
and Math.floor()
to calculate the time between each new text draw.
Use document.querySelector().innerHTML
to update the value of the selected element.
Omit the fourth parameter, step
, to use a default step of 1
.
Omit the fifth parameter, duration
, to use a default duration of 2000
ms.
const counter = { let current = start _step = end - start * step < 0 ? -step : step timer = ; return timer;};
Examples
; // Creates a 2-second timer for the element with id="my-id"
createElement
Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.
Use document.createElement()
to create a new element.
Set its innerHTML
to the string supplied as the argument.
Use ParentNode.firstElementChild
to return the element version of the string.
const createElement = { const el = document; elinnerHTML = str; return elfirstElementChild;};
Examples
const el = ;console; // 'container'
Creates a pub/sub (publish–subscribe) event hub with emit
, on
, and off
methods.
Use Object.create(null)
to create an empty hub
object that does not inherit properties from Object.prototype
.
For emit
, resolve the array of handlers based on the event
argument and then run each one with Array.prototype.forEach()
by passing in the data as an argument.
For on
, create an array for the event if it does not yet exist, then use Array.prototype.push()
to add the handler
to the array.
For off
, use Array.prototype.findIndex()
to find the index of the handler in the event array and remove it using Array.prototype.splice()
.
const createEventHub = hub: Object { thishubevent || ; } { if !thishubevent thishubevent = ; thishubevent; } { const i = thishubevent || ; if i > -1 thishubevent; };
Examples
const handler = console;const hub = ;let increment = 0; // Subscribe: listen for different types of eventshub;hub;hub; // Publish: emit events to invoke all handlers subscribed to them, passing the data to them as an argumenthub; // logs 'hello world' and 'Message event fired'hub; // logs the object and 'Message event fired'hub; // `increment` variable is now 1 // Unsubscribe: stop a specific handler from listening to the 'message' eventhub;
currentURL
Returns the current URL.
Use window.location.href
to get current URL.
const currentURL = windowlocationhref;
Examples
; // 'https://google.com'
detectDeviceType
Detects wether the website is being opened in a mobile device or a desktop/laptop.
Use a regular expression to test the navigator.userAgent
property to figure out if the device is a mobile device or a desktop/laptop.
const detectDeviceType = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i ? 'Mobile' : 'Desktop';
Examples
; // "Mobile" or "Desktop"
elementContains
Returns true
if the parent
element contains the child
element, false
otherwise.
Check that parent
is not the same element as child
, use parent.contains(child)
to check if the parent
element contains the child
element.
const elementContains = parent !== child && parent;
Examples
; // true; // false
Returns true
if the element specified is visible in the viewport, false
otherwise.
Use Element.getBoundingClientRect()
and the window.inner(Width|Height)
values
to determine if a given element is visible in the viewport.
Omit the second argument to determine if the element is entirely visible, or specify true
to determine if
it is partially visible.
const elementIsVisibleInViewport = { const top left bottom right = el; const innerHeight innerWidth = window; return partiallyVisible ? top > 0 && top < innerHeight || bottom > 0 && bottom < innerHeight && left > 0 && left < innerWidth || right > 0 && right < innerWidth : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;};
Examples
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}; // false - (not fully visible); // true - (partially visible)
getImages
Fetches all images from within an element and puts them into an array
Use Element.prototype.getElementsByTagName()
to fetch all <img>
elements inside the provided element, Array.prototype.map()
to map every src
attribute of their respective <img>
element, then create a Set
to eliminate duplicates and return the array.
const getImages = { const images = ...el; return includeDuplicates ? images : ...images;};
Examples
; // ['image1.jpg', 'image2.png', 'image1.png', '...']; // ['image1.jpg', 'image2.png', '...']
getScrollPosition
Returns the scroll position of the current page.
Use pageXOffset
and pageYOffset
if they are defined, otherwise scrollLeft
and scrollTop
.
You can omit el
to use a default value of window
.
const getScrollPosition = x: elpageXOffset !== undefined ? elpageXOffset : elscrollLeft y: elpageYOffset !== undefined ? elpageYOffset : elscrollTop;
Examples
; // {x: 0, y: 200}
getStyle
Returns the value of a CSS rule for the specified element.
Use Window.getComputedStyle()
to get the value of the CSS rule for the specified element.
const getStyle = ruleName;
Examples
; // '16px'
hasClass
Returns true
if the element has the specified class, false
otherwise.
Use element.classList.contains()
to check if the element has the specified class.
const hasClass = elclassList;
Examples
; // true
Creates a hash for a value using the SHA-256 algorithm. Returns a promise.
Use the SubtleCrypto API to create a hash for the given value.
const hashBrowser = cryptosubtle;
Examples
; // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
hide
Hides all the elements specified.
Use NodeList.prototype.forEach()
to apply display: none
to each element specified.
const hide = ...el;
Examples
; // Hides all <img> elements on the page
httpsRedirect
Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
Use location.protocol
to get the protocol currently being used. If it's not HTTPS, use location.replace()
to replace the existing page with the HTTPS version of the page. Use location.href
to get the full address, split it with String.prototype.split()
and remove the protocol part of the URL.
const httpsRedirect = { if locationprotocol !== 'https:' location;};
Examples
; // If you are on http://mydomain.com, you are redirected to https://mydomain.com
insertAfter
Inserts an HTML string after the end of the specified element.
Use el.insertAdjacentHTML()
with a position of 'afterend'
to parse htmlString
and insert it after the end of el
.
const insertAfter = el;
Examples
; // <div id="myId">...</div> <p>after</p>
insertBefore
Inserts an HTML string before the start of the specified element.
Use el.insertAdjacentHTML()
with a position of 'beforebegin'
to parse htmlString
and insert it before the start of el
.
const insertBefore = el;
Examples
; // <p>before</p> <div id="myId">...</div>
isBrowserTabFocused
Returns true
if the browser tab of the page is focused, false
otherwise.
Use the Document.hidden
property, introduced by the Page Visibility API to check if the browser tab of the page is visible or hidden.
const isBrowserTabFocused = !documenthidden;
Examples
; // true
nodeListToArray
Converts a NodeList
to an array.
Use spread operator inside new array to convert a NodeList
to an array.
const nodeListToArray = ...nodeList;
Examples
; // [ <!DOCTYPE html>, html ]
Returns a new MutationObserver and runs the provided callback for each mutation on the specified element.
Use a MutationObserver
to observe mutations on the given element.
Use Array.prototype.forEach()
to run the callback for each mutation that is observed.
Omit the third argument, options
, to use the default options (all true
).
const observeMutations = { const observer = mutations; observer; return observer;};
Examples
const obs = ; // Logs all mutations that happen on the pageobs; // Disconnects the observer and stops logging mutations on the page
off
Removes an event listener from an element.
Use EventTarget.removeEventListener()
to remove an event listener from an element.
Omit the fourth argument opts
to use false
or specify it based on the options used when the event listener was added.
const off = el;
Examples
const fn = console;documentbody;; // no longer logs '!' upon clicking on the page
on
Adds an event listener to an element with the ability to use event delegation.
Use EventTarget.addEventListener()
to add an event listener to an element. If there is a target
property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct this
context.
Returns a reference to the custom delegator function, in order to be possible to use with off
.
Omit opts
to default to non-delegation behavior and event bubbling.
const on = { const delegatorFn = etarget && fn; el