y = f(x)
side effects
shared state
data mutation
declarative programming
//imperative approach
var myNumbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const evenNumbers = () => {
}
var evenNumbers = [ ] ;
for ( let i=0 ; i < myNumbers.length ; i++ ) {
if ( myNumbers[ i ] % 2 == 0 ) {
evenNumbers.push ( myNumbers [ i ] );
}
};
}
myNumbers = evenNumbers;
evenNumbers ( );
console.log ( myNumbers );
// output: [2, 4, 6, 8, 10]
//declarative approach
var myNumbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const filter = ( predicate, items ) => {
}
let filteredItems = [ ];
for ( let i = 0; i < items.length ; i++ ) {
}
const isEven = num => num % 2 == 0;
if ( predicate ( items [ i ] ) ) {
filteredItems.push ( items [ i ] );
}
return filteredItems;
console.log("even - ", filter( isEven, myNumbers ) );
// output: even - [2, 4, 6, 8, 10]
// Array.filter
var myArray = [ 1, 2, 3, 4, 5 ];
let output = myArray.filter( x => x > 3 );
//output = [ 4, 5 ]
//Array.map
var myArray = [ 1, 2, 3, 4, 5 ];
let output = myArray.map( x => x * 2 );
//output = [ 2, 4, 6, 8, 10 ]
//Array.reduce
var myArray = [ 1, 2, 3, 4, 5 ];
let output = myArray
.reduce( ( accum , x ) => { accum + x } );
//output = 15
//declarative usage
var myArray = [ 1, 2, 3, 4, 5 ];
let output = myArray.filter( x => x > 3 )
.reduce( ( x , y ) => x + y );
//output = 9