Skip to content

Instantly share code, notes, and snippets.

@hsdhillon
Last active June 1, 2018 00:42
Show Gist options
  • Save hsdhillon/0c321f273f1b04f1f42949208af5cde0 to your computer and use it in GitHub Desktop.
Save hsdhillon/0c321f273f1b04f1f42949208af5cde0 to your computer and use it in GitHub Desktop.
Javascript References

Foreach vs Filter vs Map vs Reduce

Foreach

Takes a callback function and run that callback function on each element of array one by one. Returns nothing (undefined) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

words.forEach(function(element) {
  console.log(element);
});

Filter

Provides a callback for every element and returns a filtered array. Filter executes the callback and check its return value. If the value is true element remains in the resulting array but if the return value is false the element will be removed for the resulting array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

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"]

Map

Takes a callback and run it against every element on the array. Creates a new array with the results of calling a provided function on every element in the calling array and returns it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.map(word => `*${word}*`);
console.log(result);
// expected output: Array ["*spray*", "*limit*", "*elite*", "*exuberant*", "*destruction*", "*present*"]

Reduce (Alternatives: reduceRight)

Applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. Returns the value that results from the reduction. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment