Basic JavaScript: Replace Loops using Recursion (using a function before declaration)

Tell us what’s happening:
In this exercise the concept recursion is explained. The following code is used as an example:

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

I understand the concept and I also understand how to use it. What I don’t understand is the fact that multiply is used within the function that defines multiply without multiply being declared first. How is it known what

return multiply(arr, n - 1) * arr[n - 1];

should do when multiply is yet to be defined?

Thanks in advance!

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

that’s not exaclty true, as only once the function is called anything is executed, and at that point the function is already defined.

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Thank you for pointing that out to me.

So the way the recursion works is by drilling to the innermost value (the one that ends the loop), and working back out. Javascript parses the code twice - once to parse (“lex”) and prepare (assigning variables or functions defined globally, checking for fatal language errors…), and a second time to actually execute.

So, when your function actually runs, a variable namespace has already been assigned for it in memory. Thus, within itself, the function already exists.

As to what happens, the function “nests” itself to the innermost iteration, the one that terminates the recursion (the array index is less than zero), which returns one. Which is passed to the next-innermost iteration and multiplied by the first member of the array, and that product is then returned to the NEXT innermost and multiplied by… Until the entire recursion has backed out, giving the final sum.

The book You Don’t Know JavaScript (Yet) has a great explanation of how javascript does its interpreting as a two-pass thing, well worth the read.

Thank you, @snowmonkey. Your answer is comprehensive; it makes sense to me now. Due to circumstances it has been a while since I came here, so apologies for my late reply.

Glad to help, and welcome back! :frog::tada::tada: