JavaScript snippets from around the web
This is a dump of all the snippets I have collected over the last 18 months or so, that I’m going to document here so it’s probably going to be a mess but it’s mainly for my reference so 😛
Arrays
Straight from Wes himself.
🔥 The Array .some()
Method is super handy for checking if at least
one item in an array meets what you are looking for
1const user = {2 name: 'Scott',3 permissions: ['USER', 'CREATE_ITEM'],4}5
6// check if the user is either admin or can delete in item7const canDelete = user.permissions.some(p =>8 ['ADMIN', 'DELETE_ITEM'].includes(p)9)10// canDelete is false11
12// check if a user is either admin or can create in item13const canCreate = user.permissions.some(p =>14 ['ADMIN', 'CREATE_ITEM'].includes(p)15)16// canDelete is true
On the same note .every()
is great for checking every item in an
array meets what you are looking for.
1const people = [2 { name: 'Scott', age: 42 },3 { name: 'Sue', age: 26 },4 { name: 'Orla', age: 9 },5]6
7const canEveryoneDrink = people.every(p => p.age >= 18)8// false9
10const canSomeoneDrink = people.some(p => p.age >= 18)11// true12
13const howManyDrinkers = people.filter(p => p.age >= 18).length14// 2
Via Addy Osmani
Get the unique values of an array in JS. Use ES2015 Set()
and
...rest
to discard duplicate values.
1const uniqueArray = arr => [...new Set(arr)]2
3uniqueArray([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 0, 0, 10, 10])4// Array(9) [ 1, 2, 3, 4, 5, 6, 7, 0, 10 ]5uniqueArray([6 'London',7 'Manchester',8 'Cambridge',9 'London',10 'Greater London',11 'London',12 'Manchester',13])14// Array(4) [ "London", "Manchester", "Cambridge", "Greater London" ]
Array.from()
accepts another .map
arguments. Useful for calling
each element of a created array.
1const year = new Date().getFullYear()2const totalYears = 53
4Array.from('web')5// Array(3) [ "w", "e", "b" ]6
7Array.from(Array(totalYears), (_, i) => year + i)8// Array(5) [ 2019, 2020, 2021, 2022, 2023 ]9
10Array.from({ length: totalYears }, (_, i) => year + i)11// Array(5) [ 2019, 2020, 2021, 2022, 2023 ]
Async await
1const getAsyncStuff = async name => {2 try {3 const response = await fetch(4 `https://api.github.com/users/${name}`5 )6 return await response.json()7 } catch (err) {8 console.error(err)9 }10}
🔥 4 Ways to handle the double promise with fetch() and async+await
1const url = 'https://api.github.com/users/spences10'2
3async function go() {4 // 1. tac a promise onto the end5 const p1 = await fetch(url).then(data => data.json())6
7 // 2. double8 const p2 = await (await fetch(url)).json()9
10 // 3. capture promise in a variable11 const data = await fetch(url)12
13 // then convert it on another line14 const p3 = await data.json()15
16 // 4. create a utility function17 const p4 = await getJSON(url)18}19
20// use ... spread to get all arguments21function getJSON(...butter) {22 // then spread into the fetch function23 return fetch(...butter).then(data => data.json())24}25
26go()
Back to Top