Map and filter an array at the same time, using reduce():
const foo = [1, 2, 3, 4, 5, 6];
const bar = foo.reduce((accumulator, current) => {
if (current % 2 === 0) {
accumulator.push(current * 2);
}
return accumulator;
}, []);
bar; // [4, 8, 12]Get a random number in a range (inclusive):
Math.floor(Math.random() * (max - min + 1)) + min
Math.floor(Math.random() * (10 - 2 + 1)) + 2 // random number between 2 and 10Create a bookmarklet to clear browser storage (i.e. session storage and local storage):
javascript:(function(){sessionStorage.clear();localStorage.clear()}());Besides removeEventListener(), you may use AbortController#abort() to remove an event listener:
const { abort, signal } = new AbortController();
element.addEventListener('click', handleClick, { signal });
abort(); // removes event listenerTimeout fetch requests with AbortSignal.timeout():
fetch(url, {
// ...
signal: AbortSignal.timeout(5000), // abort after 5 seconds
});Safely parse a number:
function parseNumber(input: string) {
if (input.trim() === '') {
return;
}
const value = Number(input);
if (!Number.isFinite(value)) {
return;
}
return value;
}Do something when the DOM is ready:
window.addEventListener('DOMContentLoaded', (event) => {
// The HTML document has been completely parsed, and all deferred scripts have downloaded and executed
});Lazy load a script:
const script = document.createElement('script');
script.async = true; // or defer
script.src = 'path/to/file.js';
script.onload = () => {} // callback if needed
document.querySelector('head').appendChild(script);Promise wrapper to avoid try/catch:
function promiseWrapper(promise) {
return promise
.then((data) => [, data])
.catch((error) => [error]);
}
const [error, data] = await promiseWrapper(doAsyncStuff());- Getter accessors
- Setter accessors
- Trailing commas in object literals
- Trailing commas in array literals
- Reserved word property names
Object.create()Object.defineProperty()Object.defineProperties()Object.freeze()Object.getOwnPropertyDescriptor()Object.getOwnPropertyNames()Object.getPrototypeOf()Object.isExtensible()Object.isFrozen()Object.isSealed()Object.keys()Object.preventExtensions()Object.seal()Array.isArray()Array.prototype.every()Array.prototype.filter()Array.prototype.forEach()Array.prototype.indexOf()Array.prototype.lastIndexOf()Array.prototype.map()Array.prototype.reduce()Array.prototype.reduceRight()Array.prototype.some()Array.prototype.sort:compareFunctionmust be function orundefinedArray.prototype.sort:compareFunctionmay be explicitundefined- Property accessor of strings
String.prototype.trim()Date.now()Date.prototype.toISOString()Date.prototype.toJSON()Function.prototype.bind()JSON.parse()JSON.stringify()- Immutable
undefined - Immutable
NaN - Immutable
Infinity Function.prototype.apply()permits array-likesparseInt()ignores leading zeros- Function "prototype` property is non-enumerable
- Arguments toStringTag is "Arguments"
- Zero-width chars in identifiers
- Unreserved words
- Enumerable properties can be shadowed by non-enumerables
- Thrown functions have proper
thisvalues - Strict mode
- Modules,
import, andexportstatements - Proper tail calls (tail call optimization)
- Default parameters
- Rest parameters
- Spread syntax
- Shorthand object property/method names and computed properies
for...ofloop- Octal numbers
- Binary numbers
- Template literals
- RegExp
yanduflags - Destructuring assignment
- Unicode code point escapes
new.targetconstlet- Block-level functions
- Arrow functions
classsuper- Generators
- Typed arrays
MapSetWeakMapWeakSetProxyReflectPromiseSymbolObject.assign()Object.getOwnPropertySymbols()Object.is()Object.setPrototypeOf()- Function
nameproperty String.fromCodePoint()String.raw()String.prototype.codePointAt()String.prototype.normalize()String.prototype.repeat()String.prototype.startsWith()String.prototype.startsWith()throws onRegExpString.prototype.endsWith()String.prototype.endsWith()throws onRegExpString.prototype.includes()String.prototype[@@iterator]()Stringiterator prototype chainRegExp.prototype.flagsRegExp.prototype[@@match]()RegExp.prototype[@@replace]()RegExp.prototype[@@split]()RegExp.prototype[@@search]()get RegExp[@@species]Array.from()Array.ofget Array[@@species]Array.prototype.copyWithin()Array.prototype.find()Array.prototype.findIndex()Array.prototype.fill()Array.prototype.keys()Array.prototype.values()Array.prototype.entries()Array.prototype[@@iterator]()Array.prototype[@@unscopables]Arrayiterator prototype chainNumber.isFinite()Number.isInteger()Number.isSafeInteger()Number.isNaN()Number.parseFloat()Number.parseInt()Number.EPSILONNumber.MIN_SAFE_INTEGERNumber.MAX_SAFE_INTEGERMath.clz32()Math.imul()Math.sign()Math.log10()Math.log2()Math.log1p()Math.expm1()Math.cosh()Math.sinh()Math.tanh()Math.acosh()Math.asinh()Math.atanh()Math.trunc()Math.fround()Math.cbrt()Math.hypot()Date.prototype[@@toPrimitive]Arrayis subclassableRegExpis subclassableFunctionis subclassablePromiseis subclassableBooleanis subclassableNumberis subclassableStringis subclassableErroris subclassableMapis subclassableSetis subclassable- Prototype of bound functions
ProxyObjectstatic methods accept primitives- Own property order
- Updated identifier syntax
- Miscellaneous
Object.values()Object.entries()Object.getOwnPropertyDescriptors()String.prototype.padStart()String.prototype.padEnd()- Trailing commas in function parameter lists
- Trailing commas in function argument lists
asyncfunctions andawaitSharedArrayBufferAtomics
- Object rest/spread properties
Promise.prototype.finally()s(dotAll) flag for regular expressionsRegExpnamed capture groupsRegExpLookbehind AssertionsRegExpUnicode Property Escapes- Async generators
for await...of
Object.fromEntries()String.prototype.trimStart()String.prototype.trimEnd()Array.prototype.flat()Array.prototype.flatMap()- Optional
catchbinding Symbol.prototype.descriptionFunction.prototype.toString()