You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A conditional statement that is used at the beginning of a function to check for invalid input or unexpected conditions.
If true, the function immediately stops and returns a value or throws an error, preventing the rest of the code from executing.
Avoid side effects [aka it should be pure function]
// not pure function
const name = 'fooName'
function giveName(){
console.log('name')
}
// pure function
function giveName(name){
return `this is my name: ${name}`
}
// use arguments, and return something
Use Higher order function
functions can be inputs/outputs
callback function
is merely a function that is invoked or carried out inside another function and is passed to it as a parameter.
function makeAdjectifier(adj){
return function (str) {
return `${adj} ${str}`
}
}
const coolifier = makeAdjectifier('cool')
coolifier('conference') // "cool conference"
const mult = (a,b) => {
return a*b;
}
const calculator = (num1,num2, operator) => {
return operator(num1,num2);
}
// mult is also called callback function
console.log(calculator(5,6,mult));
Don't iterate
use map, filter, reduce
map method use HOF
iterate like for, while, for in, for of
Avoid mutability
use immutable data
immutable means the data doesnt change
// mutation (bad code!)
let data = ['a', 'b', 'c']
data[1] = 'changed'
Persitent & immutable data structures for efficient immutability
immutable data structure
never changes
Persitent data structure
have acces to prev version
Path copying
use persitent and immutable data structure
more performant
creating another node, for new data without changing the original data or replacing
lib: immutable.js, mori
Use recursion to handle repitition
doing recursion has limitation because of call stacks
some js engines have tail call optimization to solve the issue
// non tail-recursive
const recursiveInception = (n) => {
if(n === 0) return "a dream"
let dreams = recursiveInception(n-1)
return dreams + " within a dream"
}
console.log(recursiveInception(5))
// tail-recursive (dreams+)
// it use accumulator to keep track of the sequence without using additional memory for a call stack
const tailRecursiveInception = (n) => {
const incept = (n, dreams) => {
if(n === 0) return dreams;
return incept(n-1, dreams+" within a dream")
}
return incept(n, "a dream")
}
console.log(tailRecursiveInception(5))