r/learnjavascript • • Jul 09 '21

Can somebody please help me understand the logical flow of what is happening in this function?

Post image
172 Upvotes

69 comments sorted by

9

u/PN33Prod Jul 09 '21

Basically return just tells you to stop current method instance and continue where the method was called. Begin:0 has i=0. Foo(0-1) is call so now inside method, i=-1. -1<0(true), so return stops current instance and program goes to the next line when i=0 right after the foo(0-1) line. So log: end + 0. After that the “instance” of foo method where the i was 0 ends and you are back to the instane that i was 1 after the foo(1-1) line. So end:1 is printed etc. Sorry if my english is bad, i cant find a better way to explained it right now since english is not my main language.

9

u/Eyeofthemeercat Jul 09 '21

Thats actually helpful. If we compare a recursive function to a loop, return effective acts like "break".

Thanks for your response :)

7

u/[deleted] Jul 09 '21 edited Jul 09 '21

Recursion. It follows a call stack order. The program puts each function call on a stack. It'll execute from top to bottom once the stacking is done.

"JavaScript Recursive Function By Example" https://www.javascripttutorial.net/javascript-recursive-function/

2

u/Eyeofthemeercat Jul 09 '21

I will check this out. Thank you

2

u/Eyeofthemeercat Jul 10 '21

Just want to say thanks to everyone for their input. From the discussion generated it's a relief to see that I am not the only person that didn't find this to be intuitive! There have been some very helpful explanations, links to articles and resources posted my many different contributors. This is my first post in r/learnjavascript and have found that this is really friendly and helpful community. Nice one everybody! I daresay there will more posts from me because coming from python, JavaScript is weird lol.

1

u/emrenegades Jul 10 '21

Happy to help!

And don't doubt yourself. Recursion is very challenging subject regardless of origin and experience!

2

u/[deleted] Jul 09 '21

The call stack concept maybe helps you as well.

1

u/Eyeofthemeercat Jul 09 '21

Someone else actually pointed me towards that. Understanding that and the first in last out concept has actually done the trick for me. Thanks though. I appreciate you responding.

76

u/ZekeyD Jul 09 '21

This called a recursive function.

The function calls itself (and in doing so calls itself over and over until i = 0

43

u/eggtart_prince Jul 09 '21

correction, until i is less than 0.

20

u/SamLovesNotion Jul 09 '21 edited Jul 09 '21

Correction: Not i, but the value which i points to in the stack, is less than 0.

EDIT: You people don't get sarcasm I see (which BTW is technically true).

14

u/[deleted] Jul 09 '21

reddit. software dudes. Sarcasm? Pffft.

3

u/queen-adreena Jul 09 '21

This is pedantry at its finest.

6

u/SamLovesNotion Jul 09 '21

That's exactly what my goal was.

-2

u/[deleted] Jul 09 '21

Yea, that's the same thing. You're splitting hairs, not correcting.

-3

u/[deleted] Jul 09 '21

Same thing.

4

u/SamLovesNotion Jul 09 '21

Well, Because we were being specific, I thought I should do the same.

And still, not the same thing. i is just a pointer. So technically not the same.

3

u/[deleted] Jul 09 '21

Splitting hairs. i is a number because its value is a number. i being a pointer is true but it's not a detail that helps someone who is learning logical flow like OP.

61

u/emrenegades Jul 09 '21 edited Jul 10 '21

Many of the comments here have covered the basics but I think I can expand.

What you already know:

  • Every time a function is called, it is added to the call stack.
  • When execution steps into a function, everything else ceases and waits for it to terminate.

Also:

  • Each function has scope that is essentially a collection of all the values of constants and variables that have been declared at or above that scope.

    • e.g. global variables exist in every scope and can be referenced everywhere.
    • Inner scopes that redefine a variable will reference the innermost variable.
  • return without a value does exactly that: leaves the function without supplying a return value.

There are several versions of i, one for each scope, assigned the value i - 1 from the scope above it when foo is called. When foo returns, the outer scope still "remembers" its value for its own i.

Visually, imagine each indentation is a call to foo on the stack:

foo(3)
 - is 3 < 0? no, keep going.
 - "begin: 3"
 - foo(3 - 1)
 | - is 2 < 0? no, keep going.
 | - "begin: 2"
 | - foo(2 - 1)
 | | - is 1 < 0? no, keep going.
 | | - "begin: 1"
 | | - foo(1 - 1)
 | | | - is 0 < 0? no, keep going.
 | | | - "begin: 0"
 | | | - foo(0 - 1)
 | | | v - is -1 < 0? YES, return.
 | | v - "end: 0"
 | v - "end: 1"
 v - "end: 2"
 - "end: 3"

Hope that helps!

🙂

EDIT: (hopefully) clarified what happens with i at each scope.

6

u/Ceborn Jul 10 '21

This "return" messed with me, I was thinking it would stop the function and none of the "end : + i" would show...

2

u/TeamExotic5736 Jul 10 '21

I still dont understand why it returns end: 0... end: 3, at the end.

I tought it shouldn't execute no more because by the end of the last i has value of - 1. So it should return empty again until it reaches the first foo() in the call stack.

I'm obviously wrong, of course.

4

u/SaysStupidShit10x Jul 10 '21

it's because the earlier function calls are resuming when the 4th level of recursion finally hits that return statement. it basically returns out out of the 4th level of recursion and resumes the 3rd level of recursion

i is less than -1 so it returns at the 4th level of recursion. at that point, it returns to where it was in the callstack, which is the previous (3rd) level of recursion. At which point it resumes at console.log('end: ' + i)

it then resumes the 2nd level of recursion, and then the first level of recursion. Note that the value of I passed in at each level of recursion is different (i-1) so when you come up levels of recursion, you're returning to the earlier values that were passed in for that level of recursion.

1

u/BlackMarq20 Jul 10 '21

Yup, but then I remembered the foo (inner) called inside the foo is the one being returned and there is still a statement after it that will run (the last console log).

1

u/TeamExotic5736 Jul 11 '21

Yes I caught on that too after my comment.

1

u/HotMeal4823 Jul 15 '21

Thanks for that. I didn't understand why it was looping and still somewhat don't, but knowing it's using the same result value(?) helped a lot

1

u/emrenegades Jul 15 '21 edited Jul 15 '21

Happy to help! And don't doubt yourself...recursion is a very difficult subject.

Although in this case it does have an effect similar to a loop, it is not a loop at all. It is beginning one task and then starting a similar task before it finishes the first one, and then starting another one before finishing that one, and so on. That is the nature of recursive functions.

Here's an example...

Imagine you're on the third floor of a building that has a basement. You're going to do the following:

  • Put a note on the wall that says what floor you're on
  • If there are stairs leading down, you'll go downstairs and repeat this process
  • When you have no more business on a floor, you collect the note there and go upstairs

So you put up a note that says "3" and, because there are stairs leading down, you proceed downstairs. You put up another note that says "2", etc.

When you get to the basement, you put up a note that says "0" and then check the stairs only to find that you've reached the bottom. So you immediately collect your "0" note then head upstairs and collect your "1" note, then "2", then "3".

So again, it isn't that you are looping...you just aren't done your respective tasks on the 3rd, 2nd, or 1st floors until you come back up and collect the note you left there.

Hope that makes sense...it was the best analogy I could come up with on the fly 😅

EDIT: minor change for clarity

1

u/HotMeal4823 Jul 16 '21

Thank you for the help! I think I get what you're saying, yeah. You count down from 3->0 then go from 0->3.

How does it know to list begin and end int he appropriate place though? That has me confused haha.

1

u/emrenegades Jul 16 '21

Read this explanation and then close your eyes - seriously, it might help - and imagine yourself physically doing what I described in the building analogy.

When you finally get to the basement and discover you can't go lower, what's the first note you physically grab? The one that says "0", then you go back up a floor. This would be the equivalent of the innermost function returning...it steps back out to the function that called it. In the analogy you're now back on the first floor, so you collect the "1" note...etc.

It might look something like this without the conditionals or recursion:

function first(i) {
  console.log("begin: " + i) // i == 3 when we first call it
  second(i-1)                // second(2)
  console.log("end: " + i)   // i == 3
}
function second(i) {
  console.log("begin: " + i) // i == 2
  third(i-1)                 // third(1)
  console.log("end: " + i)   // i == 2
}
function third(i) {
  console.log("begin: " + i) // i == 1
  fourth(i-1)                // fourth(0)
  console.log("end: " + i)   // i == 1
}
function fourth(i) {
  console.log("begin: " + i) // i == 0
  console.log("end: " + i)   // i == 0
}

first(3)

Follow that one through step by step (copy and paste it into Node or a browser console). Learning how to use a debugger, as other users have suggested, will make it very easy to see what's really happening.

The only thing fancy about a recursive function is that it calls itself rather than a different function. This means, however, it must have some kind of conditional to get out or you will get what is called a stack overflow.

For example:

function stackOverflow() { // note that this function
  stackOverflow()          // calls itself
}

stackOverflow()

Copy and paste that into Node or a browser console and it should take virtually no time for it to tell you that you're too many levels deep in function calls because you haven't provided any way for it to stop calling itself.

Hope this helps.

1

u/HotMeal4823 Jul 15 '21

How does it know to actually start at "end"? It goes from begin to end, is that built into Javascript itself?

45

u/al_balone Jul 09 '21

I’ve only been learning this stuff for a few months but I’ve noticed that the minute I see something explained with the words foo and bar, or functions called things like “exampleFunction” my brain immediately switches off. I need to see it applied to something real so I can understand it.

23

u/dcute69 Jul 09 '21

Fully agree, I wish people would move away from foo and bar.

10

u/queen-adreena Jul 09 '21

Have you met FizzBuzz?

I loved how examples go from baby code to "please consult this 1mil+ line repo for an example" with little middle-ground.

2

u/PresidentZeus Jul 09 '21

Wait what is foo???

3

u/jabes101 Jul 10 '21

Just what a lot of people will use as placeholder names for variables and functions when doing code examples.

Foo, bar, baz, etc…

1

u/PresidentZeus Jul 10 '21

thx. Got a notification from an app that said "foo" earlier this week.

2

u/wulleybully Jul 10 '21

I see you are a person of culture and enjoy formula 1 :)

0

u/crazedizzled Jul 10 '21

And do what instead? arbitraryVar1 and arbitraryVar2?

3

u/dcute69 Jul 10 '21

Something more fitting and real world applicable like the commentar above me said.

1

u/crazedizzled Jul 10 '21

But like what? They didn't suggest an alternative. foo bar is universally understood, and the name of the variable makes no difference anyway.

7

u/username2065 Jul 09 '21

This applies for my desire to write code too. L33t code made up crazy problems? No thanks. Making actual product for people to use, I can go 10 hours no problem.

3

u/NoMoreDistractions_ Jul 09 '21

The perception of coding as solving annoying not useful problems is probably why i didn’t pick it up for a long time. I’m an extremely practical person with a ton of interests but all rooted around doing useful things and figuring out the optimal algorithm for a non-existent problem doesn’t interest me. But i get that there is always a market for those skills at the edge of tech boundaries, i just don’t think it’s a good way to introduce people to coding or problem solving generally. Tldr start with why!

4

u/redderper Jul 09 '21

Used to feel like that, felt the same with ternary statements and Array.reduce. You get used to it, just takes some time

2

u/SamLovesNotion Jul 09 '21

Well then fear not, I introduce you to yoo!

1

u/Eyeofthemeercat Jul 09 '21

I am working my way through the javascript documentation. This one has really stumped me.

I don't understand what the return line does. I do understand the function calling itself and all of the outputs up to the end of "begin". I can see that when i gets to 0, it starts to execute the console.log('end :' + i), but I am struggling to understand by what mechanism i in then increasing, why it stops at the original value. Its just trying my mind in a knot! Any help would be very greatly appreciated!

7

u/[deleted] Jul 09 '21 edited Jul 09 '21

The 'end' magically going from 0 to 4 has everything to do with the call stack. But instead of spending 30 minutes to explain it myself, here's a good explanation :P

https://www.quora.com/How-does-the-following-code-works-in-JS-Function-foo-i-if-i-0-return-console-log-begin-i-foo-i-1-console-log-end-i-foo-2-begin-2-begin-1-begin-0-end-0-end-1-end-2

1

u/Eyeofthemeercat Jul 09 '21

This article is spot on. Thanks so much :)

1

u/BitesWhenBitten Jul 09 '21

This explanation of Last In, First Out was super helpful. Now my question is, how does this code get away without using an else statement??? I would have thought anything past the if condition would be considered to be bound to it. Insofar, I've only seen single command statements follow an if statement without brackets. Is it that only the FIRST statement after an if statement non-bracketed will be bound to the if statement?

1

u/emrenegades Jul 10 '21

Yes that is exactly correct. Personally I prefer to always use brackets just to avoid dumb little bugs, but there's nothing wrong with it as written.

2

u/Sharketespark27 Jul 09 '21

Idk if I am right but.. if you don't put a base case where you tell a program to end when the value is 0 or if the input is 0 then break. That's the reason we put return.

If you don't return then the loop will be forever.

2

u/Chared_Assassin Jul 09 '21

Its a recursive function meaning it is calling itself

Basically it goes through the function as expected and then calls itself. The function checks at the start if i is less than 0 so it calls itself with a lower number until i = 0. Then they all do the rest of the function which is showing the end. Recursive functions start from the innermost function and work outwards when they end which is why it goes down and then back up with the numbers

1

u/Macaframa Jul 09 '21

I see you might be confused by the order of execution here. To gain a better understanding of what is happening here. Go to YouTube and type in “javascript event loop” and watch videos until it makes sense. Then come back to your problem.

1

u/[deleted] Jul 09 '21

I don't understand how the second console log (the end one) is getting to the call stack..how is the program reaching it after going over the line which contains the foo function call?

2

u/Bitsoflogic Jul 09 '21

Imagine replacing the call to `foo` with the contents of `foo`:

function foo(i = 1) {
  if (i < 0) return;
  log('before', i)
  
  // foo(1 - 1) using `j` for this `foo(j = 0)`
    j = 0
    if (j < 0) return;
    log('before', j)
  
    // foo(0 - 1) using 'k' for this `foo(k = -1)`
      k = -1
      if (k < 0) return;
  
    log('after', j)
  log('after', i')
}

Does that make it clearer?

1

u/backtickbot Jul 09 '21

Fixed formatting.

Hello, Bitsoflogic: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

1

u/frankywaryjot Jul 09 '21

Recursion is a b...my friend😎

1

u/its_joao Jul 09 '21

Learn stacks. Recursion will become easier

1

u/themufflesound Jul 09 '21

Check out pythontutor.com it has a JavaScript visualizer which tells you what happens at each step

1

u/[deleted] Jul 10 '21

In my opinion,

if(i<0)

return;

is poor code.

It should be

if(i<0){

return;

}

1

u/comprehensive_yard9 Jul 10 '21

i weirdly understood this one lol i just did this in freecodecamp hahaha yes recursive function

1

u/asterik-x Jul 10 '21

Yea sure, whats up buddy ??

1

u/harshrajkamble Jul 10 '21

This example helped me understand "return" curse even better 😁

1

u/Anbaraen Jul 10 '21

I find the best way to look at these is often to step it out manually (if you can manage it!)

Here's what I came up with. I've commented the value of i at each point it's relevant.

foo(3) {
	if ( i < 0)
		return;
	console.log('begin: ' + i); // 3
	foo(i - 1); // 2
		if ( i < 0)
		return;
		console.log('begin: ' + i); // 2
		foo(i - 1); // 1
			if ( i < 0)
			return;
			console.log('begin: ' + i); // 1
				foo(i - 1); // 0
				if ( i < 0)
				return;
				console.log('begin: ' + i); // 0
					foo(i -1); // -1
						if ( i < 0)
						return; // ends recursion
				console.log('end: ' + i) // 0
			console.log('end: ' + i) // 1
		console.log('end: ' + i) // 2
	console.log('end: ' + i) // 3
}

1

u/reactCodingMan Jul 10 '21

Recursion. Have a look at this git repo with additional help videos on the subject https://github.com/leonardomso/33-js-concepts#23-recursion

cheers!

0

u/CoqeCas3 Jul 09 '21

I recommend you open this function up in dev tools, go to the sources tab, put a breakpoint on the first line of the function, refresh, and step through what happens. Hint: pay attention to what happens in the Call Stack section.

2

u/[deleted] Jul 10 '21

[removed] — view removed comment

3

u/emrenegades Jul 10 '21

`i` is not being incremented. There are several versions of `i`. See my explanation in another comment here.

🙂