ARRAYS CALLBACK FUNCTIONS - PART 1

INTRODUCTION:

Callbacks are central to javascript. Infacts lots of built in javascript methods expect you to pass a callback function. So in this article, we will see some of the most used built in methods that expects you to pass a callback function and these all have to do with arrays.

To give a defination callback: A callback is a function pointer passed to another function that the latter can call for reference or purpose. Just to make things simpler, a CALLBACK function is simply a function that calls itself.

At the end of this article you should have a good understanding and uses of the following methods.

  • forEach
  • map
  • filter
  • find
  • reduce
  • some
  • every

FOREACH METHOD (.forEach()): .forEach() accepts a callback and accepts a function, and it calls it on every element in a given array. It is an array method, so we can call it on an array.

SYNTAX

  • Using anonymous function expression
    arr.forEach(function (parameter) {
       return value;
    })
    
  • Using anonymous arrow Function
    arr.forEach(parameter => {
          return value
    })
    
    Example: Printing out the array elements using .forEach()
const nums = [1, 3, 4 ,6 ,7 ,9];

nums.forEach(function(n) {
   console.log(n)
});

This outputs
// 1, 3, 4, 6, 7, 9

note: 'n' parameter represents each elements in the above given array.

Example: Printing out the sqaure value of the array elements

const nums = [1, 3, 4 ,6 ,7 ,9];

nums.forEach(function(n) {
   console.log(n * n)
});

**OUTPUT**
// 1, 9, 16, 36, 49, 81
function doubleNumber(n) {
  console.log(n * n)
};
nums.forEach(doubleNumber)
// 1, 9, 16, 36, 49, 81

note: The code above also works. But our focus in this article is callback.

let's look into a more complex array. Example 3: looping through an array of objects and accessing the book authors.

const books = [{
       title: 'Gods are not to blame',
       author: 'Rotimi',
    },
    {
       title: 'Creating impressive proposals in  Open Source Programs',
       author: 'Edidiong Asikpo',
    },
    {
       title: 'She inspires',
       author: 'Bolaji Ayodeji'    
    },
    {
       title: 'javascript Grammer',
       author: 'javascript Teacher',
    }
];

books.forEach(function (book) {
  console.log(book.arthur.toUpperCase())
});

**OUTPUT**
// ROTIMI, EDIDIONG ASIKPO, BOLAJI AYODEJI, JAVASCRIPT TEACHER.

note: 'parameter' represents each elements in the given array. Also, toUpperCase() is a method that converts strings to CAPITAL letters.

I believe you find this article useful.