I am struggling to comprehend the passing of elements from an array to a function's argument

I'm grappling with the concept of a function that I grasp.

function forEach(array, action) {
  for (var i = 0; i< array.length; i++)
    action(array[i]);
}

When we use this function, like

forEach([1,2,3,4,5], console.log);
, it essentially swaps out 'action' with 'console.log' in the body. And everything runs smoothly. Right?

However, things get a little tricky when an anonymous function is thrown into the mix.

var numbers = [1, 2, 3, 4, 5], sum = 0;

forEach(numbers, function(number) { sum += number; });

In this scenario, an anonymous function serves as an argument. How exactly does this function cycle through each element of the 'numbers' array, placing it into its parameter 'number'? It's puzzling.

To simplify matters, I could do something like:

var FindSum = function (number) {
  sum += number;
};

forEach(numbers, FindSum);

But I still find myself perplexed by how the 'FindSum' function receives a number.

Answer №1

The code in the following example is identical to the first one:

function loopThrough(array, action) {
    for (var i = 0; i < array.length; i++)
        action(array[i]); // array[i] serves as the argument
}

Hence, item represents items[i]

var items = [5,6,7];
var calculateSum = function (item) {
  total += item;
};

loopThrough(items, calculateSum); // is equivalent to calling calculateSum(5), calculateSum(6), and calculateSum(7);

Answer №2

let values = [11, 22, 33, 44, 55], total = 0; 
forEach(values, function(value) { total += value; });

In simple terms:

  1. The forEach function is used with an array (values) and an anonymous callback function.

  2. Each value in the array is passed to the anonymous function by forEach.

  3. At each iteration, the current value of the number is added to the "total".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When utilizing Wordpress PHP to group posts based on an ACF custom field, the outcome may result in an excessive number of groups

Currently, I am working on creating an organized archive of posts grouped by year. To achieve this, I am utilizing the ACF date picker and a custom function called getProdYear() to extract the year from each post's date. I have followed an example out ...

Stopping HTTP redirection in Angular 2

Attempting to simulate user login using Angular2 Http. Let's describe the situation below. There is a PHP application where users can log in through http://sample.com/login.php URL (a form exists with username and password input, users must fill in ...

There seems to be a syntax error in the script where an expression was expected but

I have attempted numerous times to solve this issue but have been unsuccessful. Here is the code I have tried: <?php while($crow = mysqli_fetch_assoc($cres)) { echo ' <div class="item" onc ...

Refreshing a DataTable by recreating it with a VueJS-populated HTML table

I am retrieving data from a database using Ajax and presenting it in an HTML table with the help of VueJS. Users can add, edit, and delete rows without any issues. However, I face a challenge when trying to incorporate a DataTable to provide users with th ...

The elements within the array are being refreshed accurately, however, a separate component is being removed

I have developed a component that has the ability to contain multiple Value components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value components, I provide input fields for name ...

Vuejs tutorial: Toggle a collapsible menu based on the active tab status

I am using two methods called forceOpenSettings() and forceCloseSettings() to control the opening and closing of a collapsible section. These methods function properly when tested individually. However, I need them to be triggered based on a specific condi ...

Continuous updates triggered by mouse movement with jQuery

Can someone help me figure out why my custom description isn't following my mouse pointer during the 'mousemove' event on an image? I've provided the HTML code below: <!DOCTYPE html> <html lang="en> <head> ...

Having difficulty rotating cube as intended using the plane and mousemove technique

I am trying to achieve a rotation effect where the cube stays flat but rotates towards the cursor in a top-down 2D fashion. I suspect that the issue might be related to how the mesh is centered against itself. Can anyone offer some assistance with this? F ...

KnockoutJS - Struggling to bind model from simple JSON array

I've been working on an application that relies on a static JSON array, without the support of a backend service. I've been attempting to bind this JSON array to the page using KnockoutJS. Although I can successfully load the JSON array and creat ...

Managing data in a database on Discord using JavaScript to automatically delete information once it has expired

Recently, I implemented a premium membership feature for my discord bot. However, I encountered an issue where the membership time starts counting down before the intended start time. To resolve this, I am looking to automatically delete the data from the ...

How can Angular 2 and Firebase be used to search for an email match within all Firebase authentication accounts?

Is there a method to verify the existence of an email within Firebase auth for all registered accounts when users sign up? Can AngularFireAuth be utilized in an Angular 2 service for this purpose? My authentication system is established, but now I am work ...

The matMul function encountered an error due to a mismatch in the inner shapes of the Tensors. The shapes provided were 684,1 and 2,1, and the transposeA and transposeB parameters were both set

I am completely new to the world of AI and tensorflow.js. Currently, I am following a Machine Learning course by Stephen Grider. I was expecting an output after running the code below, but instead, I encountered an error. Can someone please assist me? Her ...

React - Dealing with rendering issue when toggling a button using LocalStorage and State

For quite some time now, I've been struggling with a particular issue... I'm encountering challenges in using the current state to display a toggle button that can both add and remove an item from local storage. The code below manages to add and ...

How can I uniquely combine a code with an existing CSS class and make modifications to it?

I am using ngx-skeleton-loader and I would like to change the color, but I am facing some difficulties. Here is an image that illustrates the issue. When looking at the developer tools, you can see the styles action in the styles action bar. .loader ...

Setting a default value within an input tag: A step-by-step guide

const [userData, setUserData] = useState([]); const handleUserInfo = (id) => { fetch(`https://602e7c2c4410730017c50b9d.mockapi.io/users/${id}`) .then(res => res.json()) .then(data => setUserData(data)) } <inpu ...

The Facebook app is designed to require users to grant permission for the application to access their personal data

I am developing an application that replicates Facebook's functionality. When a user purchases my application, they are granting permission for my application to access their data on Facebook. Is there a way to programmatically click on the "Allow App ...

The cell text you are trying to access is beyond the allowed range

I am currently developing a shopping application, but I have encountered a problem. Up to this point, I have been parsing JSON data and creating tableview cells. However, I am facing an issue where it is showing an 'index out of range' error: ov ...

Creating a transcluding element directive in AngularJS that retains attribute directives and allows for the addition of new ones

I've been grappling with this problem for the past two days. It seems like it should have a simpler solution. Issue Description The objective is to develop a directive that can be used in the following manner: <my-directive ng-something="somethi ...

Creating a two-dimensional array and transforming it into a table with ng-repeat in Angular

I am looking to create a table using an array with the following structure: var items = [ { name: 'xxx', configurations: [ { image: 'aaa.jpg' }, { ...

The jQuery plugin functions smoothly when running on localhost, but it causes issues with the background image when deployed on the web

I created a compact plugin to show a cookie message. While testing it on my local machine, everything functioned smoothly without affecting any web pages. However, once I transferred the files to the server, I encountered issues such as: A background ima ...