JavaScript recursive function to find the sum of array elements that equals to the given target number n

Currently, I am making my way through the Javascript course available on freecodecamp. However, in one of the lessons that cover recursive functions, I have hit a bit of a roadblock.

The code snippet that is causing me confusion is as follows:

function sum(arr, n) {
        
    if(n<=0) {
        return 0;
    } else {
        return sum(arr, n-1) + arr[n-1];
    }
}

sum([10,20,30,40], 3);

In particular, I find myself struggling to grasp this line of code:

  • arr[n-1];

So, wouldn't the return statement essentially translate to sum([10,20,30,40], 3-1) + arr[3-1] resulting in 30+30 = 60?

If anyone could offer assistance on this matter, it would be highly appreciated. I welcome any guidance or direction to further resources for better understanding.

Thank you!

Answer №1

To make the original code more intuitive, let's start by placing arr[n-1] first. This will allow us to progressively expand each call to sum() towards the right.

Before we begin, let's outline what each call to sum(arr, n) will return for different values of n:

If n > 0 => arr[n-1] + sum(arr, n-1)
If n == 0 => 0

For n = 3 => arr[2] + sum(arr, 2)
For n = 2 => arr[1] + sum(arr, 1)
For n = 1 => arr[0] + sum(arr, 0)
For n = 0 => 0 

Now, let's break down the process step by step:

sum(arr, 3)
== arr[2] + sum(arr, 2) // expanding sum(arr,2) with n = 2
== arr[2] + arr[1] + sum(arr, 1)  // expanding sum(arr,1)
== arr[2] + arr[1] + arr[0] + sum(arr,0) // expanding sum(arr,0)
== arr[2] + arr[1] + arr[0] + 0
== 30 + 20 + 10 + 0

Answer №2

Let's explore a test case:

function sum(arr, n) {
    console.log(`running sum(arr, ${n})`);
    if(n<=0) {
        console.log(`returning 0`);
        return 0;
    } else {
        console.log(`calculating [sum(arr, ${n-1}) + ${arr[n-1]}]`);
        let s = sum(arr, n-1);;
        console.log(`returning [sum(arr, ${n-1}) + ${arr[n-1]}] = [${s} + ${arr[n-1]}]`);
        return s + arr[n-1];
    }
}

sum([10,20,30,40], 3);

The result will show:

running sum(arr, 3)

calculating [sum(arr, 2) + 30]

running sum(arr, 2)

calculating [sum(arr, 1) + 20]

running sum(arr, 1)

calculating [sum(arr, 0) + 10]

running sum(arr, 0)

returning 0

returning [sum(arr, 0) + 10] = [0 + 10]

returning [sum(arr, 1) + 20] = [10 + 20]

returning [sum(arr, 2) + 30] = [30 + 30]

Two other timeless examples of basic recursive functions are factorial and fibonacci, as they inherently rely on recursion. Furthermore, you can also approach multiplication in a recursive manner, thinking of it as a repeated addition of one number.

If you're looking to implement these functions in code, here's a clue for the last example:

5 * 10 can be seen as 5 + 5 * 9, which is equivalent to 5 + 5 + 5 * 8, and so forth.

Answer №3

When you pass [10, 20, 30, 40] and 3-1 as arguments to the sum function, it triggers another call to the sum function. Consider the implications of this recursive action.

Answer №4

When dealing with recursive functions, they usually work with an immediately accessible value and another value obtained by calling themselves until a base case is met.

In this scenario, the accessible parameter is a number from an array and the operation simply involves addition. The function reaches the base case when its parameters satisfy the conditions set in the code.

To grasp how the final result is achieved, consider the various iterations that occur:

  1. During the first iteration, sum([10,20,30,40], 3)

The condition in the code is not met because 3 (n) is greater than 0, triggering execution of the else branch's code.

We now have sum([10,20,30,40], 2) + arr[2]. While we do not yet know the outcome of the recursive call, we have the value of the number at the third position in the array, which is 30 (arrays typically start from 0).

  1. Moving onto the second iteration, sum([10,20,30,40], 2)

Once again, this does not satisfy the base case yet, leading to:

sum([10,20,30,40], 2-1) + arr[2-1] ->
sum([10,20,30,40], 1) + arr[1] ->
sum([10,20,30,40], 1) + 20

  1. Continuing to the third iteration, sum([10,20,30,40], 1)

At this point, we have partial results of 30 and 20. These values, along with other iteration outcomes, are all added together due to the nature of the code within the else branch—simple addition.

sum([10,20,30,40], 1-1) + arr[1-1] ->
sum([10,20,30,40], 0) + arr[0] ->
sum([10,20,30,40], 0) + 10

Another partial result of 10 has been accounted for.

  1. Lastly, the fourth and final iteration arrives, sum([10,20,30,40], 0)

Finally reaching the base case, the code executes the logic within the if branch, halting further recursion as there are no additional calls within the code. The result of sum([10,20,30,40], 0) equates to 0.

Looking back on the iterations:

• Third iteration: sum([10,20,30,40], 0) + 10 resolved to 10.

• Second iteration: sum([10,20,30,40], 1) + 20 yielded 30.

• First and initial call to the function: sum([10,20,30,40], 2) + 30 resulted in 60.

While recursive functions may seem intricate initially, grasping the concept of accumulating partial results until reaching the base case will make it easier. Patience is key to understanding this concept.

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

Incorporate a pause into a JavaScript function

Consider the following function: $(document.body).ready(function() { var o = $(".hidden"); $(".about_us").click(function() { o.hasClass("visible") ? o.removeClass("visible") : o.addClass("visible"); }); }); I am looking to add a delay to this f ...

The SVG image does not display in browsers other than Internet Explorer (IE)

I am encountering an issue with adding a menu toggle image in SVG format to my HTML. Unfortunately, the image is not displaying as expected. Here are screenshots for comparison between Explorer and Chrome: https://i.stack.imgur.com/74sqh.png https://i. ...

The Uglify task in Grunt/NPM is having trouble with this particular line of JavaScript code

Whenever I execute grunt build, Uglify encounters a problem at this point: yz = d3.range(n).map(function() { return k.map(x -> x[1]); }), An error message is displayed: Warning: Uglification failed. Unexpected token: operator (->). I have recentl ...

Refresh the page without reloading to update the value of a dynamically created object

Maybe this question seems silly (but remember, there are no stupid questions).. but here it goes. Let me explain what I'm working on: 1) The user logs into a page and the first thing that happens is that a list of objects from a MySQL database is fet ...

Customizing settings for reinitializing the Ajax range slider in Foundation 5

Is there a way to initialize foundation.slider.js and update settings through ajax? For instance, if I have a range slider with a step limit of 5, can I dynamically change it to 7 after receiving an ajax response by clicking a button? ...

When a user clicks on JavaScript, it will return true if clicked and false if

Currently working with selenium Java code and incorporating JavaScript execution using the executeScript method, as seen below: WebElement menu = driver.findElement(By.cssSelector(string1)); ((JavascriptExecutor) driver).executeScript("arguments ...

Guidelines for creating animation for a single point in SVG Polygon

Is there a way to animate the movement of a single polygon point within an SVG using velocity.js? Your assistance is greatly appreciated! <p>Changing...</p> <svg height="250" width="500"> <polygon points="0,0 200,0 200,200 00,20 ...

Transforming a React, Redux, and MUI Menu into an Electron Application

I'm in the process of transforming a web-based React + Redux + MUI application into an Electron app. The original app features a main AppBar with multiple dropdown menus, each containing menu items that interact with the app's Redux store. While ...

The Vuetify rating system seems to be having trouble displaying

I've integrated the Vuetify rating component into my app (https://vuetifyjs.com/en/components/ratings#ratings), but I'm facing an issue. Despite having Vuetify 1.5.5 installed and working with other components like buttons, the stars in the ratin ...

Tips for deactivating dropdown values based on the selection of another dropdown

There are two dropdown menus known as minimum and maximum, each containing numbers from 1 to 25. If a value is selected from the minimum dropdown (e.g. 4), the maximum dropdown should only allow values that are equal to or greater than the selected value ...

Implementing a background animation on click in React

I'm trying to create a link that, when clicked, will trigger a CSS animation to start or change its state from pause to play. Here is my current approach: import React, { useState } from 'react'; import { Link } from 'react-router-dom&a ...

Enhance a query parameter in a Node.js application

When using Node.js / Express, I define a path and pass in a request and response. My goal is to always include a seed URL parameter when this path is accessed. Initially, I set the seed query param to 0 and redirect the URL. Next, I want to randomize tha ...

Using React.js to add MongoDB documents into the database

Is there a way to directly insert documents into a MongoDB collection from a React component? I have been working on a personal project, which is a chat web application used for training purposes. For instance, when a user wants to post a new message in a ...

Utilize an Express.js controller to retrieve information from an API service and display it on the view

I need assistance with connecting an ExpressJS web app to an API system that responds only with JSON objects. The API system example is: http://example.com/user/13 response: {name:'Aesome 1', age: '13'} The ExpressJS web app cre ...

JSON Nesting with Ember.js and Rails

I'm currently developing a simple Ember / Rails application that involves multiple nested relationships. For instance: class Release < ActiveRecord::Base has_many :tracks end Upon accessing my Releases endpoint, I receive JSON data in the follo ...

Harness the Power of JSON in your JavaScript Applications

I have come across many examples on Stack Overflow discussing how to parse JSON into a JavaScript object or convert JSON to a JS object. However, I haven't found an example that demonstrates binding JSON to an already defined JS object. I am currently ...

Exploring AngularJS's capabilities with asynchronous tasks

I am in the process of developing a simple app using AngularJS. One of the key functionalities I am working on is removing items from a list. To achieve this, I have created the following code snippet: $scope.removeItem = function(item) { var toRemove = ...

How to retrieve a specific item from an array in JavaScript

I am retrieving this list from the server using PHP: ["Ak-Bulak","Balykchy","Batken"] How can I access it and insert it into select options using JavaScript? Here is what I have tried so far: for (var i in data) { $('#cities').append(' ...

"HTML and JavaScript: The search functionality fails when trying to search for a string that is sourced from an array

Could someone assist me with a comparison issue I'm encountering? I am trying to use the includes() method to compare a list in a table with a list of names stored in a string. Strangely, when I hardcode the string directly into the includes() method, ...

Struggling with updating a user in MongoDB using findOneAndUpdate and encountering a frustrating internal server error 500?

Presently, I am in the process of developing an API that is designed to update the current user in mongoDB based on the data provided in the request. However, whenever I execute findOneAndUpdate(), I encounter a 500 internal server error. (I will outline ...