Currying
Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions. It returns a new function that expects the next argument inline.
Note: The number of arguments the function takes is also called arity.
function multiply(x){
return(y) => {
return(z) => {
return x*y*z
}
}
}
console.log(multiply(1)(2)(3))
Composition
Composition is a technique where the result of one function is passed on the next function, which is passed on the next function and so on until the final function is executed and a result is computed. Function composition can be composed of any number of function.
It also helps to split the function into smaller reusable function that has a single responsibility.
let composition=function(f,g){
return function(x){
return f(g(x))
}
};
let add=function(num){
return num+10;
}
let multiply=function(num){
return num * 10
}
let ans = composition(multiply, add)
ans(5) // (5+10*10==150)
Closures
Closure is a function that preserves access to vars and arguments of the outer function, even after the outer function has completed execution. Closures are useful for hiding implementation detail in JavaScript. In other words, it can be useful to create private variables or function.
function count() {
let c = 0;
function incr() {
c = c+1;
return c;
}
return incr;
}
const generatedId = count()
generatedId() //1
generatedId() //2
Coalescing
The nullish coalescing operator ?? is a logical operator that returns its right hand side operand when its left hand side operand is null or undefined and otherwise return its left hand side operand. The nullish coalescing operator is handy when you want to use falsy values as default or simply you want to use the falsy values a valid.
const value = 0 ?? 100; //0
const value = false ?? true; //false
const value = null ?? 100; //100
const value = undefined ?? 100 //100
Reflect
Reflect is a global object that provide some useful methods for meta-programming. Reflect is not a function nor its is constructible. Its only jobs is to provide static methods for reflection.
The methods are divided into two :
1. Introspection methods which are non-destructive methods.
2. Modification methods which are destructive since they mutate the object or its behavior.
const person = {
name : 'Bob',
[Symbol('email')]: 'bob@abc.com'
}
Reflect.get(person, 'name') //Bob
Reflect.has(person, 'email') //true
Reflect.has(person, 'phone') //false
Reflect.getPrototypeOf(person) // { Consturctor ...}
Reflect.ownKeys(person) //name Symbol(email)
Reflect.defineProperty(person, 'phone', {writable: true});
Reflect.has(person, 'phone') //true
Reflect.set(person, 'phone', '12345677')
Reflect.deleteProperty(person, 'phone')
Reflect.has(person, 'phone') //false
If you liked my blog, Please do follow me on : Rhea RB
Thank you for Reading ! Happy Coding !!