JavaScript Higher Order Functions Tutorial

What are the higher-order functions?

  1. Higher-order functions do something special – they either take functions as arguments or give back functions as results.
  2. This makes them very powerful and versatile, as they can be used to abstract away common programming tasks and make your code more reusable and efficient.

List of Higher Order Functions

  1. map()
  2. filter()
  3. reduce()
  4. every()
  5. some()
  6. sort()
  7. forEach()
  8. setTimeout()
  9. setInterval()

map()

  1. The map() function is used to transform elements in an array and return a new array of the same size.
  2. You have an array of product objects and you want to create a new array containing the prices of all the products.
const products = [
    { id: 1, name: "Product 1", price: 100 },
    { id: 2, name: "Product 2", price: 200 },
    { id: 3, name: "Product 3", price: 300 },
  ];
  
const productPrices = products.map((product) => product.price);

console.log(productPrices); // [100, 200, 300]

filter()

  1. The filter() function is used to create a new array by filtering elements based on a condition.
  2. We have an array of users and you want to filter it to only include users who are active.
const users = [
    { id: 1, name: "User 1", active: true },
    { id: 2, name: "User 2", active: false },
    { id: 3, name: "User 3", active: true },
  ];

const activeUsers = users.filter((user) => user.active);

console.log(activeUsers); // [{ id: 1, name: "User 1", active: true }, { id: 3, name: "User 3", active: true }]

reduce()

  1. The reduce() function is used to accumulate values in an array and return a single result.
  2. Example: You have an array of numbers and you want to calculate the total sum of all the numbers.

const numbers = [5, 10, 15, 20];

const sum = numbers.reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

console.log(sum); // Output: 50

forEach()

  1. The forEach() function is used to iterate over the elements of an array and perform an action for each element.
  2. You have an array of users and you want to print the name of each user to the console.
const users = [
    { id: 1, name: "User 1" },
    { id: 2, name: "User 2" },
    { id: 3, name: "User 3" },
  ];

users.forEach((user) => console.log(user.name));

// Output:
// User 1
// User 2
// User 3