JavaScript recursion used to generate arrays, according to the teachings of Codecademy

      Looking to create a recursive function that calculates the powers of a number and adds each result to an array named "stack". 

This means that with each recursion, a new value will be appended to the stack.

For instance, if we use power(3, 3), our stack should then contain: [3, 9, 27].

The issue I'm encountering is getting only the last power value (27) instead of the full array. What could be wrong in my code?

// Initialize an empty array called "stack"
var stack = [];
// Recursive function implementation
function power(base, exponent) {
    // Base case 
    if (exponent === 0) {
        return 1;
    }
    // Recursion case
    else {
        stack[exponent - 1] = base * power(base, exponent - 1);
        return stack[exponent - 1];
    }
}
power(3, 3);

Answer ā„–1

Everything seems fine in your code except for the return value. Here is a slightly minified version of your code:

var task = (() => {
  var stack = [];
  function power(base, exponent) {
    return (exponent && (stack[--exponent] = base * power(base, exponent))) || 1;
  }
  power(3, 3);
  return stack;
});
console.log(task());

I personally don't prefer using recursive calls unless absolutely necessary.

In this scenario (assuming it's not just an exercise), there are alternative ways to achieve the same result. For example, using a classic for loop:

function power(base, exp){
  var result = [];
  for(var i=1; i<=exp; i++){
    result.push(Math.pow(base, i));
  }
  return result;
}
console.log(power(3, 3));

Alternatively, ES6 generators could be used:

function *power(base, exp){
  let prev = 1;
  for(var i=0; i<exp; i++){
    yield prev *= base;
  }
}

console.log([...power(3, 3)]);

Answer ā„–2

Yes, the array is not returned, but rather the final calculated product. The desired result is actually stored in the stack after the function call completes.

However, it's considered poor practice to use a global variable that can be changed by a function. Instead, it's better to create what is known as a closure for this purpose and name it powers (plural, indicating an array will be obtained from it):

function powers(base, exponent) {
    // Creating an empty array named "stack"
    var stack = [];
    // Defining the recursive function
    function power(base, exponent) {
        // Base case 
        if (exponent === 0) {
            return 1;
        } else {
            stack[exponent - 1] = base * power(base, exponent - 1);
            return stack[exponent - 1];
        }
    }
    power(base, exponent);
    return stack;
}
console.log(powers(3, 3));   

A more concise version:

function powers(base, exponent) {
    var stack = [];
    (function power(exponent) {
        return +!exponent || (stack[--exponent] = base * power(exponent));
    })(exponent);
    return stack;
}
console.log(powers(3, 3));

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

How to pass the table ID from one webpage to another using jQuery

I am dealing with 3 variations of tables that each have unique id values. My challenge is transitioning from one page to another and landing on the precise table within the new page. I'm uncertain about how to achieve this using jQuery. <table id= ...

How can you use JavaScript to create hyperlinks for every occurrence of $WORD in a text without altering the original content?

I've hit a bit of a roadblock. I'm currently working with StockTwits data and their API requires linking 'cashtags' (similar to hashtags but using $ instead of #). The input data I have is This is my amazing message with a stock $sym ...

Regular expression to limit a string to a maximum of 5 consecutive numeric characters and a total of up to 8 numeric characters

I need help creating a regex pattern that limits a string to no more than 5 consecutive numeric characters and a total of 8 numeric characters. Here are some examples: 12345 => True Yograj => True Yograj1234 ...

Organizing product categories in React

Can anyone assist me in sorting an array with currencies in a React application? I am currently rendering a list of products, each containing a price block. The data structure consists of an array of products, with each product having a subarray of prices ...

Prevent user control postback from occurring when JavaScript is active

I have been on a mission to find a solution to this issue. Hopefully, someone in this community can shed some light on it! I developed a usercontrol that utilizes .NET web controls, but I want to enhance the user experience by avoiding full postbacks. As ...

JQuery post request not providing the expected response after posting

I have a post request var prodId = getParameterByName('param'); var pass = $('#password1').val(); $.post("rest/forget/confirm", { "param" : prodId, "password" : pass }, function(data) { ...

Struggling with Rendering Dynamic Components in Vue.js? Let us lend you a helping

Hey there, I'm facing a specific situation. I have a parent component called Health Profile that displays a list of child subcomponents, each with an add button. I would like the application to work in a way that when a user clicks on the add button, ...

Incorporate create-react-app with Express

Issue - I am encountering a problem where I do not receive any response from Postman when trying to access localhost:9000. Instead of getting the expected user JSON data back, I am seeing the following output: <body> <noscript>You need to ...

Reactjs button only responds on the second click instead of the first tap

Currently, I am working on a Reactjs/nextjs project and have a video with audio button on my page. There are two things that I want to achieve: 1) I would like the button to have the "bi bi-volume-mute" class by default instead of "bi bi-volume-down". 2) W ...

What methods can be utilized to accurately determine a user's online status without continuously sending AJAX requests to the server through setInterval?

Seeking effective methods to determine a user's online status I am currently employing an inefficient technique to address this issue: I continuously send AJAX requests to the server at set intervals using setInterval, allowing the server to gauge th ...

The output in JSON format did not match the expected results

I have a code snippet that successfully generates JSON output, but it includes the characters '[' and ']' at the beginning and end, respectively. You can view the output here. $query = mysql_query("select * from questions"); $i = 0; wh ...

Enhanced dropdown menu with Vue.js

Trying to manage two select lists where their combined values equal a maximum size. For example, if the max number of people is 20 and 5 children are selected, only a maximum of 15 adults can be added, and so on. My latest attempt: Template: <div cla ...

What is the best way to store jQuery selections in a cache?

I have a need to cache approximately 100 different selections for animating. Provided below is sample code. Is there an issue with the syntax in the second example? If this isn't the correct way to cache selections, it's definitely the most popul ...

Is there a way to display points on each vertex of my geometry using React, three.js, and Three-React-fiber?

I'm trying to figure out how to utilize the pointsmaterial and points object within three-react-fiber. Currently, I have a custom geometry that I've imported from a .gltf file and I'm rendering it like this: <mesh castShadow recei ...

Using MongoDB Object as middleware in Express applications

Iā€™m facing issues trying to access the "DB" database object that gets created when the MongoDB client module establishes a connection with my MongoDB database. Currently, I am encountering an error indicating that in data.js, 'db' is not defin ...

Execute the code from https://github.com/akella/webgl-mouseover-effects on your local environment

I'm looking to create an image hover effect similar to the one on the website . The closest example I've found so far is on https://github.com/akella/webgl-mouseover-effects. I've downloaded and extracted the files, but when I try to run ...

How can I send a variable to a service using AngularJS?

I am currently working on developing an app for movie tracking, and I am fairly new to Angular. I am facing a challenge in passing a variable to this service. Instead of hardcoding the URL, I want it to be a variable. What is the best approach to achieve ...

What is the best way to transfer a JSX element from a child component to its parent component?

Is it acceptable to send the JSX element from a parent component to a child component through props? From my understanding, using `useState` to store JSX elements is not recommended. Therefore, I can't just pass a callback down to the child and then ...

The error message "email() is not a valid function when using the onclick attribute

Can anyone lend a hand? I feel like I must be overlooking something really obvious. I'm having trouble calling my function to execute my ajax call. Any assistance would be greatly appreciated. Thank you! Here is an excerpt of the HTML code: $(docu ...

Issue with xsl:include functionality in a Firefox extension

I've been working on a Firefox extension that utilizes XSL transformations with no issues. However, I encountered a problem when trying to perform an xsl:include from the XSL stylesheet. Upon importing the XSL stylesheet containing an xsl:include stat ...