Web Dev Cookbook


Callbacks & Array Methods

Map function

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

example 1

const array1 = [1, 4, 9, 16];
//pass a function to map
const map1 = array1.map(x => x * 2);
// expected output: Array [2, 8, 18, 32]

example 2

text = [" timot", "    dart", "sass    ", " e Jo"]
const cleanName = function(x){
return x.map(function(t){
return t.trim()
})
}

Arrow functions

const add = (x,y) => {
    return x+y
}

Implicit Return (only works with 1 statement in the function)

const rollDie = () => (
    Math.random() * 6 + 1 
)
const add = (a,b) => a + b

Scheduling execution

Set Timeout

setTimeout(() =>(
console.log('Hello')), 3000)

Set Interval Repeat function at set intervals

setInterval( () => (
    console.log(Math.random())
))

Clear Interval

const id = setInterval( () => (
    console.log(Math.random())
)) 
clearInterval(id)

Filter

numbers.filter( n => {
    return n < 4)
    })

Every

Some

Reduce

Newer JavaScript Features

Default Parameters

function multiply (a, b = 5){
    return...
}

Spread in function call

const nums = [12, 3, 5, 6]
Math.max(...nums)

Spread in array

const allPets = [...dogs, ...cats]

Spread in Object Literals

Useful when creating copy of objects with additional properties (take data from a form and add extra data (admin rights, userId…))

const feline = { legs: 4, family: 'felix' };
const canine = { isFurry: true, family: 'dogs'};
{ ...feline, color: 'black' }

Rest

function sum(){
    console.log(arguments)  //I can pass as many args I want when calling sum (it is not an array -> use rest)
}

function sum(...nums) {
    return console.log(nums) //nums is an array
}

Destructuring

Written on March 26, 2021