Skip to content

Latest commit

Β 

History

History
319 lines (277 loc) Β· 25.9 KB

javascript.md

File metadata and controls

319 lines (277 loc) Β· 25.9 KB

JavaScript

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());

ES5

ES2015

ES2016

ES2017

ES2018

ES2019

ES2020

Links