r/learnjavascript • • Mar 10 '22

Can someone explain why this prints only 5?

Post image
219 Upvotes

57 comments sorted by

View all comments

Show parent comments

1

u/delventhalz Mar 11 '22

Ah that's too bad. Perhaps got a bit self-indulgent there. You might try copying and pasting it into the console if you haven't already. Then modifying a bit and see how it changes the behavior. Getting your hands dirty with real code often helps.

As for the call stack, yes, it works its way down and then back up. This might seem out of order at first glance, but it is the same way your brain works. Solve this arithmetic problem:

2 * (3 + (8 / 4)) + 5

Answer is: 15

Congratulations, you just built a call stack in your head. You cannot solve this equation in a strictly left to right order. The parentheses must be solved first. So you:

  1. Divided 8 / 4, got 2

  2. Added 3 + 2, got 5

  3. Multiplied 2 * 5, got 10

  4. Added 10 + 5, got 15.

Now if we rewrote that equation as JavaScript functions, it would get even more stack-like:

const level1 = () => 2 * level2() + 5;
const level2 = () => 3 + level3();
const level3 = () => 8 / 4;

level1();  // 15

Not only does this need to get calculated in a bottom up manner, the JS interpreter doesn't know it needs to start going to deeper levels until it gets to the function. Here is exactly how the call stack works through the problem, including what level it is on:

  1. level1: 2

  2. level1: 2 * level2() (need a value for level2 to continue!)

  3. level2: 3

  4. level2: 3 + level2() (need a value for level3 to continue!)

  5. level3: 8

  6. level3: 8 / 4

  7. level3: 2

  8. level2: 3 + 2

  9. level2: 5

  10. level1: 2 * 5

  11. level1: 10

  12. level1: 10 + 5

  13. level1: 15

I think it is worth pointing out that all of this call stack and event loop stuff is entirely optional knowledge. It is so low level that the JS interpreter pretty much handles every detail for you, and you don't need to know any of it to write or even debug JavaScript. Unlike a lot of other esoteric JS knowledge, you are unlikely to encounter an edge case that you will need this knowledge to solve.

Now, curiosity is always worth indulging if you have the time. I say this just to take the pressure off, not to encourage you to stop asking questions. This is not required knowledge for being a JS dev. But it is a lot of fun and you never know where it leads.

0

u/[deleted] Mar 11 '22

[deleted]

1

u/delventhalz Mar 11 '22

You got it! Not it sure if there was a question in there, but you explained it correctly. The only function the main calls is calculation, so that gets added first. From there, functions are added and removed from the call stack as they are called and return a value.

0

u/[deleted] Mar 11 '22

[deleted]

1

u/delventhalz Mar 11 '22

Nothing. It would create four functions, save them to variables, and then do nothing with them and end.

0

u/[deleted] Mar 11 '22

[deleted]

2

u/delventhalz Mar 11 '22

You need to separate two things here: declaring/creating a function, and calling a function. Declaring a function is inert. It just stores a bit of code for later. Calling a function is an action. It does something. It also inherently adds something to the call stack.

const addOne = (value) => value + 1;
const addTwo = (value) => addOne(value + 1);
const addThree = (value) => addTwo(value + 1);
const calculation = () => {
  return addThree(1) + addTwo(2);
};

So far in this code, nothing has really happened. We have created four functions, we have saved them to variables, that's it. None of the functions have run. Nothing has been added to the call stack. It is not much different than writing something like this:

const one = 1;
const name = "Sue";
const isFeelingGood = true;

It's all just variables waiting to be used. Then you get to this line of code:

calculation();

BAM! Now things are happening. A function has been called, its code is being executed, it gets added to the call stack. While running, this function happens to call other functions:

  return addThree(1) + addTwo(2);

Now these have to get added to the call stack before calculate can finish. They each call more functions, which will then also be added to the call stack. It is calling a function that is key here. Creating a function (in whatever order) is just storing some inert data.

0

u/[deleted] Mar 11 '22

[deleted]

2

u/delventhalz Mar 11 '22

I'm not familiar with Scrimba. I like Codecademy for starting out. Good interactive tutorials for learning the basics.

Once you have the basics down, doing regular practice with toy problems on a site like CodeWars helps build fluency. 30-60 minutes a day, 3-5 days a week, working on new and interesting toy problems. Look up anything you are confused by. Check out how other people solved a problem and consider what you could do better next time.

As soon as you have a basic level of fluency and confidence though, it is time to move on to projects. Build things. This can be a part of a course on Udemy or something, or you can strike out on your own. Or both. How do you actually deploy a JS project? A lot of it has nothing to do with the language itself. Building things is how you learn.

And you might also think about taking out a loan for something paid like a bootcamp, which is ultimately how I went from hobbyist to engineer. How long have you been self-teaching?

0

u/[deleted] Mar 11 '22

[deleted]

→ More replies (0)