Bo dinglesTM - -   Bright Lightbulb Graphic Ideas   - -

The Web Developer Bootcamp 2024

Colt Steele

Back to JavaScript Index Page


JavaScript Array Callback Methods
Array Callback Methods References

JavaScript Array Callback Methods PDF

JavaScript Arrow Functions

Array Callback Methods are methods that are built specifically to works with arrays. These methods use the arrow function syntax.

Here are some of these methods:




forEach

forEach() expects a function as an argument, then runs that function, for each element in an array. The forEach() method does not run if the array is empty. Example:

  • // create an array
  • let nums = [1, 2, 3, 4, 5];
  •   
  • // create a function to print an input (number) to the console
  • function print(number) {
    • console.log(number);
  • }
  •   
  • // so for each number in the (nums) array,
  • // run the function (print) to output them to the console
  • nums.forEach(print);
So forEach will run a function on every element of an array. However, when using forEach(), you do not usually define an external function. You would define the function within the forEach() statement, like so:
  • nums.forEach(function (number) {
    • console.log(number);
  • })
This is done because you don't need an external function, you only need this function within the forEach to run while you are processing the array.

*note: forEach() is not used that much anymore, now we use for Of.




map

map() creates a new array with the results of running a "callback function" on every element in the original array. map() does not execute the function for empty elements. map() does not change the original array.

So map(), takes the original array, changes it in a "callback" function, and returns the results as a new array. Example:

  • // create original array
  • const texts = ['rofl', 'lol', 'omg', 'yeppers'];

  • // run the callback function to change the original array data and output it to a new array
  • const caps = texts.map(function(change) {
    • return change.toUpperCase();
  • )}
console.log(texts); will return ['rofl', 'lol', 'omg', 'yeppers'] and,
console.log(caps); will return ['ROFL', LOL', 'OMG', 'YEPPERS']

So map() is generally used when you want to change every element of an array, in some fashion. Map creates a new array when run but will not run on an empty array.




filter

filter(): method creates a new array filled with elements that pass a test provided by a function. This will test every element in the array and return either true or false. If the element returns true, it is added to the new array.

  • The filter() method does not change the original array.
  • The filter() method does not execute the function for empty elements.

lets create an array to work with:

  • const nums = [9, 8, 7, 6, 5, 4, 3, 2, 1];

If we create a filter method to return the numbers in the array that are odd, it could look like this:

  • const odds = nums.filter(n => n % 2 === 1)
  • % is the mod operator. it determines the remainder, of n divided by (in this case) 2.
  • if n is an even number this will return 0 (false)
  • if n is an odd number this will return 1 (true)
  • the callback function returns the numbers where n % 2 = 1 and stores them in the new array, odds

and if we print out odds, it would return:

  • [9, 7, 5, 3, 1]

*note that this does not change the original array. nums is still equal to [9, 8, 7, 6, 5, 4, 3, 2, 1]. Instead, filter creates a new array, odds that holds the returns from the callback function [9, 7, 5, 3, 1].




some

some(): Always returns true or false. This method checks if any array element passes a test (provided as a callback function). The some() method executes the callback function once for each array element, returns true (and stops) if the function returns true for any one of the array elements. The some() method returns false if the function returns false for all of the array elements. The some() method does not execute the function for empty array elements. The some() method does not change the original array.

Example: const exams = [80, 82, 92, 78, 70, 90, 89, 81, 77];
if we run

  • console.log(exams.some(score => score > 75));
we get true because some of the exam scores are > 75.

but if we run

  • console.log(exams.some(score => score < 65));
we get false because none of the exam scores are < 65.




every

every(): Always returns true or false. This method executes a function (provided as a callback function) for each array element, and returns true if the function returns true for all elements. The every() method returns false if the function returns false for one element. The every() method does not execute the function for empty elements. The every() method does not change the original array

Example: const exams = [80, 82, 92, 78, 70, 90, 89, 81, 77];
if we run

  • console.log(exams.every(score => score > 65));
we get true because every one of the exam scores are > 65.

but if we run

  • console.log(exams.every(score => score < 80));
we get false because not every one of the exam scores are NOT < 80.

==========================================================

Another example:
Say we wanted to pass several arrays into a function for processing. Let's use three "number" arrays and test to see if all of the numbers in each array are even. A Callback Function would be perfect for this. Remember, a Callback Function is a function that takes a function as an argument.

Lets set up our basic function:

  • const allEvents = function(arr) {}
We are creating a function "allEvents" which takes one argument "arr". We will write the Callback function that will check each array within this function.

Let's set up our arrays for testing:

  • allEvens([2,4,6,8]);
  • allEvens([1,4,6,8]);
  • allEvens([1,2,3]);
We are calling allEvents() and passing in an array for processing by the callback function.

In the Callback Function, we will use every() to test if EVERY element in the array, is an even number:

  • const allEvents = function(arr) {     // this is the initial function where we pass our array into the variable arr
    • return arr.every(function(num) {     // this will return the results of this "callback function"
      • return num % 2 === 0;     // this will return boolean if num is odd or even to the "callback function"
    • });
    }

So we have an array and we want to check if all the elements are even numbers [1,4,6,8]

We want to pass this array into our allEvens() function like so: allEvens([1,4,6,8]); and the array is passed into the function variable, arr

The callback function then runs the every() method on arr (array passed in) and because of the nature of the every() method will return true or false based on the test set on the next line.

The every() method then test's every item in the array (arr) and returns true or false depending whether or not num % 2 === 0, which is then returned to the Callback Function which in turn returns the results (true or false) to the initial function called, allEvens().

So for our three arrays, this would be the returned results:

  • allEvens([2,4,6,8]);     // returns true - all numbers ARE even
  • allEvens([1,4,6,8]);     // returns false - all numbers ARE NOT even
  • allEvens([1,2,3]);     // returns false - all numbers ARE NOTeven

*note: we could also use an arrow function to simplify our code like so:

  • const allEvens = arr => arr.every(num => num % 2 === 0);




reduce

reduce(): method executes a reducer function for array element and returns a single value, the function's accumulated result. Essentially, this method reduces an array down to a single value. The reduce() method does not execute the function for empty array elements. The reduce() method does not change the original array.

The basic syntax is:

  • array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

    • function(): A function to be run for each element in the array (required)

    • total: the initialValue, or the previously returned value of the function (required)
    • currentValue: the value of the current element (required)
    • currentIndex: the index of the current elemen (optional)
    • arr: the array the current element belongs to (optional)

    • initialValue: a value to be passed to the function as the initial value (optional)

This works extremely well if want to add an array full of numbers. For example:

  • const nums = [3, 5, 7, 9, 11];

  • nums.reduce((total, currentValue) => {
    • return total + currentValue;
  • });

This returns 35 because 3 + 5 = 8 + 7 = 15 + 9 = 24 + 11 = 35, thus reducing the array down to a single element which is the sum of all of the elements.

*note that this does not change the original array.

You can also shorten and simplify the code with an Implicit Return and an Arrow Function:

nums.reduce((total, currentValue) => total + currentValue); returns the same result 35.

You are not limited to addition, you could perform any mathematical function:

  • const nums = [3, 5, 7, 9, 11];
  • nums.reduce((total, currentValue) => total - currentValue); returns -29


You could aslo add the optional initialValue paramater to alter the reduce, like so:


  • nums.reduce((total, currentValue) => total - currentValue, 100); would return 71 because you are telling the reduce method to start at 100.


You are also not limited to mathematical functions. You could do anything that would return a single value such as find the lowest, or highest number.


  • num.reduce((min, val) => {
    • if (val < min) {
      • return val;
    • } else {
      • return min;
    • }
  • })

This will obviously return 3. It runs through the Callback Function starting with 3 and compares it to the next number in the list until it reduces the entire array down to a single return, in this case, the lowest number.




find

find(): method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found. The find() method does not execute the function for empty elements. The find() method does not change the original array.


Back to Top