What could be the reason for the undefined return from .forEach method?

While I have come across several questions on this particular topic , none of them have been able to provide me with a solution.

Let's take a look at the data I am working with:

 const testsMap = {
            0: ["just", "test"],
            1: ["bla", "asdf"]
        }

 const testArray = [{
    id: "1",
    segments: null,
    tests: [{
            id: "1",
            segments: "1"
        },
        {
            id: "2",
            segments: "0"
        }
    ]
},
{
    id: "2",
    segments: "1",
    tutorials: [{
            id: "1",
            segments: "1"
        },
        {
            id: "2",
            segments: "0"
        }
    ]
}];

My objective here is to achieve the desired output without utilizing .map() or .reduce methods, as I intend to overwrite the existing array. Here's what I'm aiming for:

[{
    display: true,
    id: "1",
    segments: null,
    tests: [{
            display: true,
            id: "1",
            segments: "1",
            newSegments: ["bla", "asdf"]
        },
        {
            display: true,
            id: "2",
            segments: "0",
            newSegments: ["just", "test"]
        }
    ]
},
{
    display: false,
    id: "2",
    segments: "1",
    tutorials: [{
            id: "1",
            segments: "1"
        },
        {
            id: "2",
            segments: "2"
        }
    ]
}];

The function I have written appears like this - it includes some helper functions which can be disregarded, as the main focus is on the fact that the function returns undefined:

function SOtest () {
  const returnedValue = testArray.forEach(test => {
    test.newSegments = test.segments ? testsMap[test.segments] : [];
    test.display = helperFn(); // will assign true/false to the test property

    if (test.display) {
      test.tests.map(t => {
        t.newSegments = t.segments ? testsMap[t.segments] : [];
        t.display = helperFn(); // will assign true/false to the test property
      })
    }
    return test;
  })
  return returnedValue;
}

The issue I am facing is that the forEach loop operates correctly when executed in isolation in the console, but once I try to return it, it results in undefined.

What could I possibly be overlooking here?

Answer №1

forEach function does not have a return value. It simply iterates through elements, allowing you to modify element data during the iteration.

Therefore, you can update your SOtest function as follows:

function SOtest () {
  testArray.forEach(test => {
    test.newSegments = test.segments ? testsMap[test.segments] : [];
    test.display = helperFn(); // will add true/false to the test prop

    if (test.display) {
      test.tests.map(t => {
        t.newSegments = t.segments ? testsMap[t.segments] : [];
        t.display = helperFn(); // will add true/false to the test prop
      })
    }
  })
  return testArray;
}

Answer №2

As stated in the documentation of mdn forEach

The forEach() function executes the callback function for each element in the array. It differs from map() and reduce() as it always returns undefined and cannot be chained. It is commonly used to perform side effects at the end of a chain.

Answer №3

MDN states that:

When using .map(), a new array is returned with each element being the result of the callback function.

On the other hand, .forEach() returns undefined.

If you need the elements to be contiguous in the array, it is recommended to use .map(). Otherwise, .forEach() will suffice.

Sources:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

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

steps for integrating react-pannellum library into react/ionic

Trying to integrate a 3D panorama view into my React Ionic app, but encountering an error while attempting to install using either of the following commands: npm install --save react-pannellum npm install --save pannellum > npm WARN config global `-- ...

Creating a method for a Discord Bot to communicate through a Webhook (loop)

I am looking to enhance my bot's functionality by implementing a webhook triggered by a specific command. Once activated, the webhook should send a message at regular intervals. The idea is to obtain the token and ID of the created webhook, and then ...

Dynamic styles object for React components with inline styles

I have a styles object let styles = { step_div:{ height:'150px', } } I'm trying to display multiple div elements with different colors using React class Layout extends React.Component{ constructor(props) { super(props); ...

A Vue component library devoid of bundled dependencies or the need for compiling SCSS files

My current challenge involves the task of finding a way to publish our team's component library. These components are intended to be used by various internal applications within our organization. I have specific requirements: The library must be acc ...

I am attempting to achieve a smooth transition effect by fading in and out the CSS background color using JQuery and AJAX

Can anyone help me with my issue related to using Ajax to fadeIn a background color in beforeSend and fadeOut in success? I seem to have made some mistakes but can't figure out what went wrong. var data={ ...

What is the best way to change the value of a boolean array in React?

In my component, I maintain an array of boolean values as a state. When the value is false, I need to change it to true. this.state = { checkedPos: [] } handleChange(index, reaction) { if (!this.state.checkedPos[index]) { this.state.ch ...

How can I iterate through each element of MySelector in the callback function of jquery-ui's draggable function?

When using: jQuery(MySelector).dragabble( start: function( e, ui ) { } ) In the start function: The start event provides $(this) with the current dragged element from MySelector. How can I loop through each element in MySelector to apply additional code ...

What is the key to ensuring the content in your canvas adapts to different screen sizes

Greetings! I wanted to extract the values from this specific meta tag: <meta name="viewport" property="viewport" content="width-device-width, initial-scale=1"> To retrieve content from a meta tag using JavaScript, I used the following code snippet: ...

Differences between HTTP request errors and response errors(Note: This

Currently, I am researching $http interceptors and noticed that there are requestError and responseError functions available. 1) Can you explain the distinction between requestError and responseError? 2) Under what circumstances does requestError get t ...

How can I effectively develop a versatile user interface for a website using Ruby on Rails that is compatible with all

Currently, I am in the midst of developing a web application using Ruby on Rails. Occasionally, I encounter challenges with cross-browser compatibility when it comes to CSS and Javascript. Are there any strategies you recommend to reduce these issues dur ...

Pausing until the user clicks the button again

I have implemented two buttons on this page - one with a class of 'arrow-up' and the other with a class of 'arrow-down'. Clicking on the 'arrow-down' button will smoothly scroll down to the next section, while clicking on the ...

Tips for refreshing the page without losing the values of variables

In my simulation.jsp file, I have the following code that retrieves simulation data from a struts2 action: $(document).ready(function() { var data='<s:property escape="false" value="simInfos" />'; } Once I perform the simulation with this ...

What is the process for clearing the cache of a crawling URL?

Currently, I am operating a crawler that gets triggered through an expressjs call. However, whenever I make the same request again, the crawler runs once more but indicates that all routes have already been completed. I even went to the extent of deleting ...

Issue with the Z-Index property not functioning as expected on unordered lists within a dropdown menu

I have a dropdown menu that opens to the left, but it is displaying underneath the content. I attempted adjusting the z-index of the content to 1 and the dropdown to 2, however, this did not resolve the issue. Here is a sample in jsFiddle: https://jsfiddl ...

How to disable or enable a submit button in jQuery 1.8

Recently, I upgraded from jquery version 1.5.2 to 1.9 and encountered an issue with my disabled buttons not functioning properly. The buttons should become enabled after the form fields are filled out, allowing the user to either remove or save the infor ...

Providing a callback function along with the specific execution context for it to be executed

myFn is a function that executes an asynchronous task and triggers the callback upon successful completion. SearchController.prototype.show = function (query) { this.searchService.myFn(arg1, this.myCallback); //I want to preserve the reference of `th ...

Having trouble accessing and setting the values of a JSON array retrieved using $.get method in JavaScript outside of the function

Executing the following code snippet results in the desired values being displayed in console.log: var q; $.get('/ajax_subscribers', { code: 'qyhskkcnd'}, function(returnedData){ q = returne ...

Performance of basic arithmetic operations on small arrays using NumPy

It's uncertain whether there is a solution for this question other than accepting the overhead and moving forward, but there's always a possibility. I'm performing simple mathematical operations on small 1D NumPy arrays (6 to 10 elements) w ...

What is the best way to achieve a transparent background for an element?

Having trouble making elements transparent in the background for mobile view with React. I've attempted adding background-color and background with a value of transparent to various classes, but it's not working as intended. Any suggestions on h ...

Submit the form and additional information in a single AJAX request in Django

Seeking assistance with a straightforward task. The objective is to utilize AJAX POST to move data from a form along with additional information. The challenge lies in extracting this data from the form later on, as it constitutes an entire line. $(func ...