Favor expressions/declarations over statements
Declarative programming paradigm
Computation is made through evaluation of mathematical functions
Object-oriented JS get tricky
First class citizen functions
es6
Any application state change that is observable outside the called function other than its return value
Writing to a file - file
Writing to the network - network server
console.log - javascript console
Modifying any external variable or object property - object
Separate your side effects from your program logic
extend
refactor
debug
test
maintain
input1
output1
Given the same input, will always return the same output
Side effects
let state = 10;
function isValid() {
if (state == 10)
return 'valid';
else
return 'invalid';
}isValid() // 'valid'function mutateState() {
state = state + 1;
}
mutateState()isValid() // 'invalid'Side effects
Inconsistent output
Add dependencies as arguments
Erase side effects
function isValid(state) {
if (state == 10)
return 'valid';
else
return 'invalid';
}isValid(10) // 'valid'isValid(11) // 'invalid'No side effects
Consistent output
map
reduce
filter
for
forEach
for in
const data = [1, 2];
function multArrBy2(array) {
const newArr = [];
for (let i = 0; i < array.length; i++) {
newArr.push(array[i] * 2);
}
return newArr;
}
console.log(multArrBy2(data)) // [2, 4] function multiply(a) {
return function(b) {
return a * b;
}
}
const multiplyBy2 = multiply(2);
console.log(
data.map(multiplyBy2)
); // [2, 4]const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]function greeting(msg, name) {
console.log(msg + ' ' + name);
}
// greeting('Hello', 'GDG')
function greetingCur(msg) {
return function(name) {
console.log(msg + ' ' + name);
}
}
// greetingCur('Hello')('GDG')
const sayHelloTo = greetingCur('Hello');
sayHelloTo('GDG')A curried function always returns another function with an arity of 1 until all of the arguments have been applied
The process of combining two or more functions to produce a new function.
Pure functions are easier to test
Lots of reuse - less code to test
functors, applicatives, monads
RamdaJS
lodash-fp
@franciscomags
@FranciscoMSM
Do you want to know more?
https://github.com/MostlyAdequate/mostly-adequate-guide https://medium.com/javascript-scene
code