Show Menu
Cheatography

Javascript Tricks Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

spread, rest, destru­ctu­ring...

const [, host] = id.split('@')
 
let [a, b] = [0, 1]
 
const { a } = { a: 3 } // a = 3
 
let [first] = [0, 1] // _.first
 
const {realName: alias} = {realName: 2} // alias === 2
 
function verifyUser({ realName: alias }) { // using alias }
 
function defaults({ a, b } = { a: 1, b: 2 }) {}
 
[a, b] = [b, a] // swap
 
// Pass to function that expects separate multiple arguments // Much like Function.prototype.apply() does let numbers = [9, 4, 7, 1]; Math.min(...numbers); // 1
 
[...document.querySelectorAll('div')] // NodeList to Array
 
[...arguments] // function arguments to array function logArguments(...args) {} // another way
 
let user = { first: "chris", last: "burgin" } let userCopy = {...user}; // new object, not by ref
 
console.log({myVar, otherVar})

arrays

[...Array(3)] // [0, 1, 2]
 
let ages = [12, 19, 6, 4]; ages.find(age => age >= 18); // 19 ages.findIndex(age => age >= 18); // 1
 
// de-duplicate array (not collection) dedupe = array => [...new Set(array)]
 

jsx

<c { ...{ foo: 1 } } foo={2} />
 
<с { ...{ user, fudge, bits } } />

math

~-1 = 0

functions

{ let c = 1 } // scoped function
 
f => f // noop
 
const throwIfMissing = () => {     throw new Error('Missing parameter'); } const func = (requiredParam = throwIfMissing()) => {}

strings

string.includes(substring)
 
let numString = `${num}`; // cast to string
 
// string to array const str = "aabbccaaaaaaaccc"; const result = [...str]

classes

// abstract class
class Note {
  constructor() {
    if (new.target === Note) {
      throw new Error('Directly constructed.')
    }
  }
}

await / async

function getJSON(url) {
  return new Promise(function(resolve, reject) {
    request(url, function(err, res, body) {
      resolve(body);
    });
  });
}
//
async function main() {
 try{  
  var data = await getJSON();
  console.log(data); // NOT undefined!
 } catch(e){}
}
//
main();