Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Sure, but it's probably easier to read written like this:</p> <pre><code>var reverseArray = function(x,indx,str) { if (indx === 0) { // Termination condition return str; // return default } else { return reverseArray(x, --indx, str + " " + x[indx]); // recur on x, reduce indx, update default } } </code></pre> <p>Recursion is just a function calling itself, right? The important thing is the termination condition that prevents the function from calling itself forever. In this case that's this line:</p> <pre><code>if (indx === 0)… </code></pre> <p>As long as indx is not 0, the function will continue to call itself with updated arguments. The subsequent call does the same thing, but the final product <code>str</code> contains the value passed from the parent call to <code>reverseArray</code>. Eventually indx reaches zero and the value of str is the combined value passed down from parent to child. That is what is returned by the line:</p> <pre><code>return str; // ' lime peach orange apple' </code></pre> <p>It gets returned to its parent, and its parent returns that to its parent and so on until the top-most frame is reached.</p> <pre><code>arr = new Array('apple', 'orange', 'peach', 'lime'); reverseArray(arr,arr.length,""); // ['apple', 'orange', 'peach', 'lime'], 4, "" +['apple', 'orange', 'peach', 'lime'], 3, "" + " " + x[3] = " lime"; ++['apple', 'orange', 'peach', 'lime'], 2, " lime" + " " + x[2] = " lime peach"; +++['apple', 'orange', 'peach', 'lime'], 1, " lime peach" + " " + x[1] = " lime peach orange"; ++++['apple', 'orange', 'peach', 'lime'], 0, " lime peach orange" + " " + x[0] = " lime peach orange apple"; // indx == 0, so this string returns </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload