The Beauty of JavaScript: Simplifying Array Navigation. Second Edition, page 83

I'm having trouble understanding the mechanics of this code. Here's what I've got:

function forEach(array, action) {
  for (var i = 0; i < array.length; i++) 
    action (array[i]);  
}
var numbers = [1, 2, 3, 4, 5], sum = 0;
forEach(numbers, function(number) {
  sum += number;
});
console.log(sum);

I can see that sum =+ number; is passed to forEach, iterating through the array numbers. However, I'm struggling with the specifics of how this process unfolds. Substituting function(number) {sum =+ number} in place of action like this:

for (var i = 0; i < [1, 2, 3, 4, 5].length; i++)
  function(number) {
    sum += number;
  } (array[i]);
}

doesn't make sense, and it doesn't execute properly. The following does work:

var numbers = [1, 2, 3, 4, 5], sum = 0;
for (var i = 0; i < numbers.length; i++)
  sum += (numbers[i]);
debug(sum);
console.log(sum);

This version is more concise and functional but I'm still trying to grasp the underlying principles. How do you arrive at this point? Essentially, what is happening behind the scenes?

Any assistance on clarifying this would be greatly appreciated. This topic appears fundamental to Haverbeke's methodology, so understanding it thoroughly is crucial.

Answer №1

When using the forEach function, it will execute the specified action for every element in an array.

Essentially, forEach simplifies a loop operation similar to the one shown below:

for (var i = 0; i < numbers.length; i++){
    sum += numbers[i];
}

The notation action(array[i]) may have caused confusion. Just remember that this syntax is essentially performing the same task as action(array[i]).

In the case of forEach, the function invocation is handled within the code itself -- at the action(array[i]). This allows you to pass a function without manually calling it each time.

In simple terms, forEach functions by applying a specified function to each element in a provided array.

For further clarification, imagine the following example (assuming forEach aligns with the concept discussed):

var greetings = ["Hello", "Hi", "How are ya"];

function printGreeting(greeting){
    console.log(greeting, "Greg");
}

forEach(greetings, printGreeting);

In this scenario, printGreeting is triggered for every value within the greetings array by utilizing greetings[i].

Any tasks accomplished through a traditional for loop across an array can often be streamlined using the forEach method.

To delve deeper into this topic, explore the standard Array.prototype.forEach() at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Answer №2

Translating it properly, in line with the suggestion made by @FelixKling (even if not directly mentioned by him), can be done like this:

let list = numbers;
let process = function(num) {
    total += num;
}
for (let j = 0; j < list.length; j++) {
    process(list[j]);
}

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

Is it possible to enable unknown keys for multiple schema objects simultaneously using Joi Validation?

I have a multitude of validator files each containing nearly a hundred schema objects. My goal is to validate unknown keys for all of them simultaneously. I've managed to figure out how to do it for a single object, as shown below. Is there a way to a ...

Having trouble loading the Google API using getScript. Is displaying a ReferenceError message: "Variable google not found."

I am attempting to dynamically load the Google API using the getScript() method for implementing a "Place Autocomplete Address Form". For more information, you can visit this link: https://developers.google.com/maps/documentation/javascript/examples/places ...

Differences between MobX local state and global state

I am currently working on a React project using mobx to manage the application state. For dump components that interact with external data sources (such as ajax calls, filtering or mapping arrays), I simply manipulate the data in those components. Howeve ...

Utilizing an array within a separate class

I am looking to pass an array of values from one class to another. In the ActivityReceiver class, I receive an array and store it in a String array called inkLevel[][]. After receiving the array, I need to extract specific values. For this purpose, I have ...

Ways to obtain parameter from URL in Express without diving into the request object

const express = require('express'); const app = express(); app.use('/', anyroute); // in anyroute file router.route('/:id').get(controlFunction) controlFunction(req, res, res)=> { // Here we can get the "id" fr ...

Using the `forEach` method nested within another `forEach

I'm facing an issue with the useEffect hook where it seems to not be rendering correctly. My cardArticle is only concatenating the last array and that's it. Below is the code snippet: const [articles, setArticles] = useState([]); const [cardA ...

Requesting input from the user to generate two arrays

import java.util.Scanner; public class Ch7AssignArrays1 { public static void main(String[] args) { int[] population = new int[5];// array to store populations for counties String[] county = new String[5]; //array to store county names ...

In three.js, it is important to understand that Vertex and Vector3 are not simply

When I started using three.js revision 48, I created vertices connected by lines without any issues. However, upon updating to revision 65 from 48, an error message appeared stating that Vertix is deprecated and should be replaced by Vector3. Unfortunately ...

Transforming a document into a byte array and back again

There are multiple ways to convert a file to a byte array and write a byte array to a file on storage. My goal is to specifically convert a java.io.File object to a byte array and then convert that byte array back to a java.io.File. Without writing it ou ...

Starting a new React project

prtScn I'm encountering an issue while trying to initiate a new react app in Visual Studio Code. I have been following the given instructions as follows: in the visual code terminal : create-react-app sali (sali is the name) npm install node node_m ...

Basic node.js server that responds with HTML and CSS

I have successfully created a basic http server to send an HTML file as a response. However, I'm struggling with how to also send a CSS file so that the client can view the HTML page styled with CSS in their browser. Here is my current code: var htt ...

I often find myself puzzled by a couple of lines of source code within the express framework

Within the file ./lib/express.js, function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; mixin(app, proto); mixin(app, EventEmitter.prototype); app.request = { __proto__: req, app: ...

Selenium is encountering a maximum call stack size error while attempting to access Highcharts

This particular issue is a bit complex. My goal is to retrieve highchart data from a selenium-controlled Chrome browser using the driver.execute_script method and injecting some JavaScript: driver.execute_script("return $('#chartID').highcharts( ...

What is the best way to display text from a header box across multiple line boxes in real time on an HTML page?

Looking to enhance an HTML layout with a header box and line comment boxes. <textarea name="order[header_comments]"></textarea> The line comment boxes are structured as follows: <textarea name="line_comments[0][line_comments]"></tex ...

Change from one value to another using a decaying sinusoidal wave

Can someone help me come up with a formula that will smoothly transition from a starting value to an end value over a specified time using a Sin or Cos wave? I'm attempting to replicate a bouncing effect like the one shown in my sample using CSS and ...

Having trouble uploading an image using the Cloudinary API in a Next.js project

I am currently working on a page meant for creating posts. Initially, the page was designed to handle multiple image uploads. However, I made some adjustments so that it can now accept only a single image upload. Unfortunately, after this modification, the ...

Am I making a mistake with my Ajax request parameters?

My approach to formulating an Ajax request using prototype involves the following method: function updateServerStep(stepNumber){ alert("updating server step to " + stepNumber); var params = {stepNumber:stepNumber}; alert(params.stepNumber); ...

Retrieve the associative array from the user input by utilizing jQuery

How can I create an associative array from a form containing multiple text inputs using jQuery (or directly in JS)? Here's an example of the form: <form> <input type="text" name="name[13]" value="test 1" /> <input type="text" name="nam ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...

Attempting to effectively store and retrieve an array using MySQL

Currently, I am working with an array of PlayerNames that are part of a specific 'clan' and I need to save this information so that when the server is loaded, it can easily loop through all the entries. Below is what I have set up in my MySQL Ta ...