What is the reason that the reduce function is only effective when the final argument is explicitly stated?

I'm having trouble understanding the reduce method. What is the reason why

const sumOfCubes = nums => nums.reduce((a,b) => a + Math.pow(b, 3))

does not function properly, while

const sumOfCubes = nums => nums.reduce((a,b) => a + Math.pow(b, 3), 0)

works as expected?

Answer №1

When using only one argument, array.reduce(fn) functions similarly to this:

for (let i = 1, a = array[0]; i < array.length; ++i)
  a = fn(a, array[i]);

This means that in your scenario, the first value of 2 is not cubed, resulting in an incorrect sum.

Adding a second argument changes the behavior to:

for (let i = 0, a = secondParameter; i < array.length; ++i)
  a = fn(a, array[i]);

By passing 0 as the second parameter, the value to add on the first iteration is correctly set to 0, leading to each value in the array being cubed.

Answer №2

In the context of `reduce`, it is important to specify the initial value of the accumulator, as demonstrated in the second example by passing `0` as an argument.

For more information on this topic, check out the following resource:

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

As pointed out by @VLAZ, if you do not provide an initial value, the reduce function will use the first element of the array but skip it:

InitialValue Optional A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used and skipped. Calling reduce() on an empty array without an initialValue will throw a TypeError.

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

The issue with json arises when utilizing $.ajax without the definition$

Attempting to make this code work properly Javascript $.ajax({ url: '/endpoint/json/', //Update the path to your JSON file. type: "post", dataType: "json", //Remove the "data" attribute if not needed. data: { ...

Proper method of defining an action in Vuex

Do you think it's sufficient to create vuex-actions as simple as a1, without chaining then/catch calls? Or should I always go with creating Promises as in a2 (and also adding a reject branch)? Appreciate your insights... import Vue from 'vue& ...

Unable to retrieve an array in SAPUI5 and assign it to a JSONModel

I encountered an issue with accessing an array where I stored data from a model read operation. The array, named aData, contains row data for a table and everything seems to be working correctly as all the data is present. This code snippet is executed af ...

Angular JS Introductory Module

Currently, I am encountering an issue in AngularJS 1.2.15 marked by $injector:modulerr. Interestingly, the application runs smoothly when hosted on a MAMP Apache server locally, but encounters errors when running on a node server, generating the error mess ...

AngularJS' $rootScope is experiencing issues with creating internal variables

My app utilizes $rootScope.requestObj to store key-value pairs representing filters. Throughout the entire application, $rootScope.requestObj is considered a singleton and behaves as expected. However, when I call an external API, I have a service that t ...

An error has occurred in NodeJS: Value undefined is out of the acceptable range for an unspecified property in the options

I am currently leveraging worker_threads in nodejs to handle the task of reading multiple files and processing the rows for subsequent insertion into a database (using oracle-db). The volume of data I deal with is substantial, typically exceeding one mill ...

Guide to profiling resources in Node.js applications

When developing Node.js applications, it's important to keep track of how your code is performing in terms of memory and IO. By monitoring these metrics, you can identify which parts of your code are causing delays or consuming excessive resources. Th ...

Saving an array to a database in Concrete5

I have created a block where multiple names can be dynamically added. However, when I click save and return to edit the block, the newly added names are not visible. I suspect there is an issue with saving to the database. Can someone please assist me with ...

Attempting to showcase the information in my customized SharePoint Online list through a Web Part Page utilizing AngularJS

<script> //AngularJS Code goes here var appVar = angular.module('listApp', ['ngRoute']); appVar.controller("controller1", function($scope){}); function FetchEmployeeData($scope, EmployeeList){ var reque ...

Update the page with AJAX-loaded content

I am currently utilizing a .load() script to update the content on a webpage in order to navigate through the site. This is resulting in URLs such as: www.123.com/front/#index www.123.com/front/#about www.123.com/front/#contact However, I am encountering ...

Creating new Vue components is happening towards the end of the loop

I am currently encountering an issue with my Vue components. I have structured them in a hierarchy where I have a post-index component displaying all posts, containing a post-view component for individual posts, and within that, a post-like component to ha ...

Monitoring variables in different AngularJS controllers

I have a component named histogram demo which includes a distinct controller with a variable known as $scope.selectedElements. I aim to monitor this variable in the primary appCtrl controller. How can I achieve access to this variable without using $rootSc ...

Retrieving the output of JavaScript code in C#

How can I retrieve the value from a window.prompt() alert box in my C# Code Behind file? I know it's a simple line of JavaScript, but I want to execute it and get the result within my Code Behind. Whether it's done through a <script> tag in ...

Issue encountered with Jquery Carousel: "Unable to access property 'safari' as it is undefined"

Having recently set up a duplicate of my website in a development directory, I've come across an issue with the jQuery Carousel not working properly. An error message now pops up saying: Uncaught TypeError: Cannot read property 'safari' of ...

Conflicting events arising between the onMouseUp and onClick functions

I have a scrollbar on my page that I want to scroll by 40px when a button is clicked. Additionally, I want the scrolling to be continuous while holding down the same button. To achieve this functionality, I implemented an onClick event for a single 40px s ...

What steps should I take to retrieve the value from the daterange picker?

I am currently working on developing a user-friendly date range picker that can be used to select dates from a drop-down menu and pass them to an SQL query. At this stage, I am focused on handling the selected date and displaying it in an h1 tag. Options ...

Can the table be automatically updated on page reload?

My goal is to populate a table using $.ajax(), but the content is not showing up when the page first loads. Is there something missing in my implementation of the $.ajax() function? Here's the HTML structure: <div class="row"> <div clas ...

What could be causing my router UI in angular.js to malfunction?

Having an issue with routing not functioning as intended, here is the relevant code: $urlRouterProvider. otherwise('/list'); $stateProvider. state('home', { abstract: true, views: { 'header': { templateUrl: &apos ...

When making a POST request from the client-side JavaScript, the req.body is coming back as an empty

I have been encountering several questions related to the same topic, but unfortunately, none of them have resolved my issue. Hence, I am posting a new question here. My objective is to send a POST request from client-side javascript to the Backend using ...

Tips for preserving the status of a sidebar

As I work on developing my first web application, I am faced with a navigation challenge involving two menu options: Navbar Sidebar When using the navbar to navigate within my application, I tend to hide the sidebar. However, every ti ...