1
[Task] Rewrite the following code in modern javascript form
chat-to.devA function that invokes itself is called a recursive function. Typically, you use a recursive function when a process must be performed more than once, with each new iteration of the process performed on the previously processed result. The use of recursion isn’t common in JavaScript, but it can be useful when dealing with data that’s in a tree-line structure, such as the Document Object Model (DOM). However, it can also be memory- and resource-intensive, as well as complicated to implement and maintain. As such, use recursion sparingly, and make sure you test thoroughly. uses a recursive function to traverse a numeric array, add the numbers in the array, and add the numbers to a string.
```js
function runRecursion(){
var addNumbers = function sumNumbers(numArray, indexVal,resultArray){
// recursion test
if(indexVal == numArray.length)
return resultArray;
//perform numeric addition
resultArray[0] += Number(numArray[indexVal]);
//perform string concatenation
if(resultArray[1].length > 0) {
resultArray[1] += " and";
}
resultArray[1] += numArray[indexVal].toString();
// increment index
indexVal++;
// call function again, return results
return sumNumbers(numArray,indexVal,resultArray);
}
// create numeric array, and the result array
var numArray = ["1", "35.4", "-14","44", "0.5"];
var resultArray = new Array(0,""); // necessary for the initial case
// call function
var result = addNumbers(numArray,0,resultArray);
// output
document.writeln(result[0] + "
"); document.writeln(result[1]); } ``` ### html session ```html
"); document.writeln(result[1]); } ``` ### html session ```html
Some content
``` The result of running is a page output of: 66.9 1 and 35.4 and -14 and 44 and 0.5 do you like challenges like this? then create a post here on the site and type in the same code but with modern javascript features ;-) Or come and talk about this code in this chat room -> [JAVASCRIP CHAT ROOM](https://chat-to.dev/chat?q=javascript-room)You must log in or register to comment.