Hello all,

Can someone explain the attached code please..And in particular, how the program execution flows between the different scope blocks.. Thanks

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Recursion</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
//<![CDATA[

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] + "<br />");
   document.writeln(result[1]);
}
//]]>
</script>
</head>
<body onload="runRecursion();">

Recommended Answers

All 6 Replies

The code is finding sum of array values using recursive method

var numArray = ;
Here you can change the values and check the result. as it is called onload, everytime you have to open link in fresh page, refresh may not work

sumNumbers()
functions accepts 3 arguments, data array, current array index, and result array

function checks if current index is >= to lenght then it returns to calling part.
other wise it adds current index array value to 0th index of result array
it also build a string of array values and store in 1st index of result array.

Now index value is increment and again same function is called with incremented index value.

Oggiemc,

Scopes here are maybe not obvious.

The outer function forms a "closure" giving each instance of the inner function access to numAray , resultArray and result .

In javascript, objects (including arrays) are equated and passed by reference (not by value). Consequently:

  • the formal parameters numArray and resultArray are actually references to the original arrays declared in the outer function
  • numArray and resultArray need not be formally passed.

Meanwhile, numbers and strings are equated and passed by value (not by reference).

Taking advantage of this knowledge (and by rearranging things a bit), the code can be considerably simplified:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Recursion</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
onload = function() {
   var numArray = [1, 35.4, -14, 44, 0.5];
   function addNumbers(total, indexVal) {
      return (indexVal >= numArray.length) ? total : addNumbers(total+numArray[indexVal], ++indexVal);
   }
   document.writeln(addNumbers(0, 0) + '<br />' + numArray.join(' and ');
}
</script>
</head>
<body>
</body>
</html>

Airshow

Nice construction Airshow, that's efficient coding;
for further optimization purposes the function recursion can also be omitted I think:

var args=[1,35.4,-14,44,0.5];
document.writeln(function(args,x,v){for(x in args)v+=args[x];return v+"<br>"+args.join(' and ')}(args,0,0))

TIII! How you doing, I've not seen you around much recently.

Airshow

Whoops, there's mistake in my code.

//replace
document.writeln(addNumbers(0, 0) + '<br />' + numArray.join(' and ');
//with
document.writeln(addNumbers(0, 0) + '<br />' + numArray.join(' and '));

Airshow

Yeah, you forgot to close the writeln( [...] ; but that's not a big deal. Your literal conditional has found a very elegant use of a recursive call there.
Regards.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.