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 10
Create 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 listener
Timeout 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
:compareFunction
must be function orundefined
Array.prototype.sort
:compareFunction
may 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
this
values - Strict mode
- Modules,
import
, andexport
statements - Proper tail calls (tail call optimization)
- Default parameters
- Rest parameters
- Spread syntax
- Shorthand object property/method names and computed properies
for...of
loop- Octal numbers
- Binary numbers
- Template literals
- RegExp
y
andu
flags - Destructuring assignment
- Unicode code point escapes
new.target
const
let
- Block-level functions
- Arrow functions
class
super
- Generators
- Typed arrays
Map
Set
WeakMap
WeakSet
Proxy
Reflect
Promise
Symbol
Object.assign()
Object.getOwnPropertySymbols()
Object.is()
Object.setPrototypeOf()
- Function
name
property String.fromCodePoint()
String.raw()
String.prototype.codePointAt()
String.prototype.normalize()
String.prototype.repeat()
String.prototype.startsWith()
String.prototype.startsWith()
throws onRegExp
String.prototype.endsWith()
String.prototype.endsWith()
throws onRegExp
String.prototype.includes()
String.prototype[@@iterator]()
String
iterator prototype chainRegExp.prototype.flags
RegExp.prototype[@@match]()
RegExp.prototype[@@replace]()
RegExp.prototype[@@split]()
RegExp.prototype[@@search]()
get RegExp[@@species]
Array.from()
Array.of
get 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]
Array
iterator prototype chainNumber.isFinite()
Number.isInteger()
Number.isSafeInteger()
Number.isNaN()
Number.parseFloat()
Number.parseInt()
Number.EPSILON
Number.MIN_SAFE_INTEGER
Number.MAX_SAFE_INTEGER
Math.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]
Array
is subclassableRegExp
is subclassableFunction
is subclassablePromise
is subclassableBoolean
is subclassableNumber
is subclassableString
is subclassableError
is subclassableMap
is subclassableSet
is subclassable- Prototype of bound functions
Proxy
Object
static 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
async
functions andawait
SharedArrayBuffer
Atomics
- Object rest/spread properties
Promise.prototype.finally()
s
(dotAll) flag for regular expressionsRegExp
named capture groupsRegExp
Lookbehind AssertionsRegExp
Unicode Property Escapes- Async generators
for await...of
Object.fromEntries()
String.prototype.trimStart()
String.prototype.trimEnd()
Array.prototype.flat()
Array.prototype.flatMap()
- Optional
catch
binding Symbol.prototype.description
Function.prototype.toString()