Reverse Iteration with forEachRight

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the forEachRight function in JavaScript. This function executes a provided callback function for each element of an array in reverse order. We will learn how to use this function to perform operations on array elements in reverse order.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/ToolsandEnvironmentGroup -.-> javascript/debugging("`Debugging`") subgraph Lab Skills javascript/variables -.-> lab-28314{{"`Reverse Iteration with forEachRight`"}} javascript/data_types -.-> lab-28314{{"`Reverse Iteration with forEachRight`"}} javascript/arith_ops -.-> lab-28314{{"`Reverse Iteration with forEachRight`"}} javascript/comp_ops -.-> lab-28314{{"`Reverse Iteration with forEachRight`"}} javascript/debugging -.-> lab-28314{{"`Reverse Iteration with forEachRight`"}} end

Here's how to execute a function for each array element in reverse

To execute a function for each array element, starting from the array's last element, follow these steps:

  1. Clone the given array using Array.prototype.slice().
  2. Reverse the cloned array using Array.prototype.reverse().
  3. Use Array.prototype.forEach() to iterate over the reversed array.

Here's an example code snippet:

const forEachRight = (arr, callback) => arr.slice().reverse().forEach(callback);

You can test the function by running the following code:

forEachRight([1, 2, 3, 4], (val) => console.log(val)); // '4', '3', '2', '1'

To get started with coding, open the Terminal/SSH and type node.

Summary

Congratulations! You have completed the Execute Function for Each Array Element in Reverse lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like