Cheat Sheets

JavaScript

Created: 2017 December 1st

Updated: 2020 July 27th

Edit this page on GitHub

Document Design Mode

Edit a web page, set the design mode to on.

1document.designMode = 'on'
2// make edits, then
3document.designMode = 'off'

Copy an array

1// initial array
2const cats = [`Darcy`, `Leo`, `Boris`]
3// copy array
4const copyCats = [...cats]

output:

1["Darcy", "Leo", "Boris"]

Combine two arrays

1// array 1
2const cats = [`Darcy`, `Leo`, `Boris`]
3// array 2
4const people = [`Scott`, `Islem`, `Tom`, `George`]
5// all
6const catsAndPeople = [...cats, ...people]

output:

1["Darcy", "Leo", "Boris", "Scott", "Islem", "Tom", "George"]

Remove item without mutating

1// array 1
2const cats = [`Darcy`, `Leo`, `Boris`]
3// array 2
4const people = [`Scott`, `Islem`, `Tom`, `George`]
5// all
6const catsAndPeople = [...cats, ...people]
7// remove Tom
8const withoutTom = [
9 ...catsAndPeople.slice(0, 5),
10 ...catsAndPeople.slice(6),
11]

Tom is left out of the new array party, sorry Tom

output:

1["Darcy", "Leo", "Boris", "Scott", "Islem", "George"]

Reverse an array

So, .reverse() will mutate the original array so it’s a good idea to make a new array.

1const cats = [`Darcy`, `Leo`, `Boris`]
2// reverse array
3const reverseCatNames = [...cats].reverse()

output:

1# cats
2["Darcy", "Leo", "Boris"]
3# reverseCatNames
4["Boris", "Leo", "Darcy"]

Reverse a string

There’s a .reverse() method for arrays, so if you split your sting into an array then you’ll be able to reverse it.

1'racecar'.split('').reverse().join('')

output:

1racecar

New array from existing

Return one new entry for every existing entry: .map()

1const originalArray = [1, 2, 3]
2const newArray = originalArray.map(item => item * 2)
3console.log(newArray)

output:

1[ 2, 4, 6 ]

Return new array filter

Return a new array with only some of the existing entries: .filter()

1const originalArray = [1, 9, 4, 2, 42]
2const newArray = originalArray.filter(item => item > 5)
3console.log(newArray)

output:

1[ 9, 42 ]

Return one new thing only

Return one new thing only: .reduce()

1const originalArray = [
2 'Alice',
3 'Bob',
4 'Charlie',
5 'Bob',
6 'Bob',
7 'Charlie',
8]
9const numberOfBobs = originalArray.reduce((accumulator, item) => {
10 if (item === 'Bob') {
11 return accumulator + 1
12 } else {
13 return accumulator
14 }
15}, 0)
16console.log(numberOfBobs)

output:

13

Sum all even numbers from array

1const arr = [0, 1, 2, 3, 4, 5, null, 6, 9]
2
3function addEven() {
4 return arr.reduce(
5 (acc, cur) => (cur % 2 === 0 ? acc + cur : acc),
6 0
7 )
8}
9
10addEven(arr)

Return the first duplicate number

1function firstDuplicate(arr) {
2 // empty array to use to check incoming array against
3 let checkArray = {}
4
5 // loop it
6 for (let i = 0; i < arr.length; i++) {
7 // check that array element against
8 // checkArray
9 if (checkArray[arr[i]] !== undefined)
10 // if there's no matching item then
11 return arr[i]
12 // append to the checkArray
13 else checkArray[arr[i]] = i
14 }
15 return -1
16}

Async await with axios and GraphQL

1const axios = require('axios')
2
3axios({
4 url: 'https://spotify-graphql-server.herokuapp.com/graphql',
5 method: 'post',
6 data: {
7 query: `
8 {
9 queryArtists(byName:"Andy C") {
10 name
11 id
12 image
13 albums {
14 name
15 image
16 }
17 }
18 }
19 `,
20 },
21}).then(result => {
22 console.log(result.data)
23})

Remove vowels from string

Use a regular expression:

1'replace vowels from string'.replace(/[aeiou]/gi, '')

Output:

1"rplc vwls frm strng"

With JavaScript functions:

1'replace vowels from string'
2 .split('a')
3 .join('')
4 .split('e')
5 .join('')
6 .split('i')
7 .join('')
8 .split('o')
9 .join('')
10 .split('u')
11 .join('')

Output:

1"rplc vwls frm strng"

Closure examples

Closures are the ability for a child function (or inner function) to access variables from a higher level scope even after the functions have been called (closed or closed over).

The running of a function within a function:

1function greeting(salutation = '') {
2 const sarcasm = () => {
3 return [...salutation]
4 .map((char, i) => char[`to${i % 2 ? 'Upper' : 'Lower'}Case`]())
5 .join('')
6 }
7 return function (name) {
8 return `${sarcasm()} ${name}`
9 }
10}
11
12// run the function
13const sayHiya = greeting('Hiiiya')
14const sayHello = greeting('Hellooo')
15
16// now the function is closed but we can still
17// access the variables inside it
18console.log(sayHiya('scott'))
19console.log(sayHello('margret'))

Private variables:

1function createGame(gameType) {
2 let score = 0
3 return function increment() {
4 score++
5 return `Your game of ${gameType} score is ${score}.`
6 }
7}
8
9const cribbage = createGame('Cribbage')
10const bridge = createGame('Bridge')
11
12console.log(cribbage())
13console.log(cribbage())
14console.log(cribbage())
15console.log(cribbage())
16console.log(bridge())
17console.log(bridge())
18console.log(cribbage())

Output:

1Your game of Cribbage score is 1.
2Your game of Cribbage score is 2.
3Your game of Cribbage score is 3.
4Your game of Cribbage score is 4.
5Your game of Bridge score is 1.
6Your game of Bridge score is 2.
7Your game of Cribbage score is 5.

Mock and endpoint

Use a mock endpoint to test against for auth forms.

1const wait = n => new Promise(resolve => setTimeout(resolve, n))
2
3const mockFetch = url =>
4 wait(1000).then(() => ({
5 status: 200,
6 body: {
7 url: 'http://bbc.co.uk',
8 },
9 }))
10
11mockFetch(`${endpoint}`).then(response => {
12 console.log('=====================')
13 console.log(response.status)
14 console.log(form.userEmail.value)
15 console.log(form.userPassword.value)
16 console.log('=====================')
17 response.status === 200
18 ? (location = response.body.url)
19 : console.error(`incorrect`)
20})

List all image URLs from a web page

Need to quickly grab a load of images from a page?

1let images = document.querySelectorAll('img')
2Array.from(images).map(i => {
3 console.log(i.src)
4})

<div> cannot appear as a descendant of <p>

If you’re looking for where this is happening, in console you can use:

1document.querySelectorAll(' p * div ')

Truncate a string

Shorten a string! Define the start and the end of the string you want to return:

1const myString = 'ABCDEFG'
2const myTruncatedString = myString.substring(0, 3)
3// The value of myTruncatedString is "ABC"

Current year one liner

1const copyrightYear = new Date().getFullYear()

Fizz Buzz

Classic FizzBuzz loop.

1for (let i = 1; i <= 100; ++i) {
2 let output = ''
3 if (i % 3 === 0) {
4 output += 'Fizz'
5 }
6 if (i % 5 === 0) {
7 output += 'Buzz'
8 }
9
10 if (output === '') {
11 output = i
12 }
13
14 console.log(output)
15}

Prototypal Instantiation

Instantiation patterns are ways to create something in JavaScript.

1var person = function (name) {
2 var obj = Object.create(objMethods)
3 obj.name = name
4 return obj
5}
6
7var objMethods = {
8 sayHello: function () {
9 console.log(`${this.name} says hello!`)
10 },
11 changeName: function (newName) {
12 var oldName = this.name
13 this.name = newName
14
15 console.log(`${oldName} has changed their name to ${this.name}`)
16 },
17}
18
19// Implementation
20var person1 = person('Austin')
21person1.sayHello()
22person1.changeName('Derek')
23person1.sayHello()

Output:

1Austin says hello!
2Austin has changed their name to Derek
3Derek says hello!

Change Page Font Size

Want to change the font size on a page? Here you can target the while document, but could change html with p, span whatever.

1document.getElementsByTagName('html')[0].style['font-size'] = '10px'