Posts

JavaScript Loop [forEach, map, reduce, each,filter]

ECMAScript5 (the version on Javascript) to work with Arrays. forEach  - Iterates through every item in the array and do whatever you need with each item. [ 'C' , 'D' , 'E' ]. forEach ( function ( element , index ) { console . log ( element + " is the #" + ( index + 1 ) + " in musical scale" ); }); // Output // C is the #1 in musical scale // D is the #2 in musical scale // E is the #3 in musical scale In case , more interested on operation on array using some inbuilt feature. map  - It creates a new array with the result of the callback function. This method is good to be used when you need to format the elements of your array. // Let's upper case the items in the array [ 'bob' , 'joe' , 'jen' ]. map ( function ( elem ) { return elem . toUpperCase (); }); // Output: ['BOB', 'JOE', 'JEN'] reduce  - As the name says it reduces the array to a single valu