How does javascript actually work?
Imagine getting this question during an interview or how about this,
explain the difference between asynchronous and synchronous in Javascript,
or maybe they ask you to explain this statement.
Javascript as a single threaded language that can be non-blocking.
Oh boy! in this video we're going to help you answer those questions.
This is a video you may need to visit a few times as you progress.
To really get it.
So don't feel discouraged, if you don't feel hundred percent confident.
Just keep watching it and you'll get it.
Now, we don't need to know how javascript works internally to write a program.
But it is important to learn.
I see a lot of people who have been developers for years and none know this.
It's like being a pilot and not knowing how an airplane can fly.
OK, that's a little bit dramatic there but you get my point.
So let's start. First, what is a program?
Well, a program has to do some simple things.
It has to allocate memory.
Otherwise, we wouldn't be able to have variables or even have a file on our computer.
It also has to parse and execute, scripts, which means it read and run commands.
OK.
Now, we also know that from our previous discussion, there's the javascript engine that each browser implements.
And in Chrome, it's the V8 and the V8 engine reads the javascript that we write. It changes into machine
executable instructions for the browser.
Now the engine, consists of two parts, a memory heap and a call stack.
Now, the memory heap,
this is where the memory allocation happens.
And don't worry, we're going to talk about this.
And then the call stack,
this is where your code is read and executed.
It tells you where you are in the program.
So let's simplify this and show you what did I mean. I have Sublimetext over here,
and for us to allocate memory in the memory heap,
well, it's as simple as doing 'const a equals to one'. We've just allocate a memory.
Now, when we assign this, the javascript engine is going to remember that oh! yeah, 'a' has a value of 1.
We've just used up the memory heap.
And, I can keep going on, on and on like this, right?
I can keep copying and pasting and changing these variables to 'b' and 'c' and I can change the values
to a 100 and maybe here it will be 10.
Cool.
Now, what's an issue that we see with this?
This is something called a memory leak that you're going to hear as you become a developer.
And what we've done here is we've created all these variables. These global variables that are in the
memory heap.
But you see this box right?
And with all memory we have a limited amount, that we can actually have.
So by increasing the number of variables that we have, imagine if I had just this page full of variables
and instead of just numbers, they're like very very big arrays.
Well, memory leaks happen when you have unused memory,
such as let's say, we're now using the variable 'a',
but it's still there, well, by having unused memory just laying around,
it fills up this memory heap. And that's why you might hear, why global variables are bad.
Global variables are bad because we don't forget to clean up after ourselves,
we fill up this memory heap and eventually the browser will not be able to work.
All right, so that's memory.
Let's talk about the call stack.
What is that?
Well, again, with a call stack we can have something like this, 'console log' we'll go '1', 'console log 2', and then
finally 'console log 3', if I run this code, in my browser terminal,
well I get, '1, 2, 3'. So the call stack, if you remember, that's what it reads and executes our scripts.
So what the call stack does it reads the first line, console dot log,
it gets put, in the call stack.
So the javascript engine says oop!, console dot log has been added.
Let's pop it onto this call stack. And then it runs it and creates one, then it says, OK, I'm removing the
first console log as I just finished running it, I'm going to place the second console log
into my call stack, adds it on here and says, yah! execute 2 and then it removes that, it pops it and
then gets console log 3 and logs console log 3,
and then finally removes it.
But let's have a bit more of a complex example here to demonstrate this point.
Imagine, I have something like this.
I have a function 'const one'
and inside this function, we have another function 'const two' and for now it's not really going to do much.
It's gonna console dot log '4' and then in here we'll just say, we run the 'two' function.
So if I copy and paste this, and place it into our console and I run 'one', I get 4 and ignore this error.
here, it's just related to my app in the browser.
But you see that we get 4.
So what happened here according to the Call Stack?
Well, if we have the call stack here, we first ran the 'one' function.
So on top of the call stack the 'one' function gets run.
And as we enter into this call stack, we see that we run another function 'two'.
So 'two' goes on top of the call stack, and now we run the 'two' function which is console dot log.
So we have, console dot log '4' that's run inside of the '2' function.
So now that we read this the call stack is going say, OK,
there's nothing else inside of this.
I'm going to run console locg 4.
So it's going to print out number 4 here.
It's going to remove that from the call stack, and then remove the 'two' and then remove the 'one', because
it's just been called.
And the call stack is now empty.
All right.
Awesome.
Now let's revisit the statement from the beginning of the video.
Javascript is a single threaded language that can be nonblocking. Single threaded means that it has only
one call stack.
And one call stack only, you can only do one thing at a time.
And as you saw, a call stack is first in last out.
So whatever's at the top the call stack gets run first then below that, below that, below that till the
call stack is empty.
Now, other languages can have multiple call stacks and these are called multithread.
You can also see how that might be beneficial to have multiple call stacks, so that we don't keep waiting
around for stuff.
Why was javascript designed to be single threaded? Well, running code on a single thread can be quite
easy, since you don't have to deal with complicated scenarios that arise in multithreaded environment.
You just have one thing to worry about.
And, when I say issues with multithreaded environment, you can have such thing as deadlocks. Now, guess what,
you just learned what synchronous programming means, synchronous programming simply means, line one
gets executed then line two gets executed and then line three gets executed.
The latter, can start before the first finishes, so this console log '2', doesn't start until console log
finishes. And console log '3' doesn't start until these above two finish. Because well, we've looked at the call
stack because of the call stack.
Now, you may have heard of the site stack overflow.
If you're a developer you use it on a daily.
And have you ever wondered what stack overflow means?
Well Stack Overflow
is this, when a stack is overflowing.
Kind of like we talked about memory leaks and how the memory heap of a javascript engine can overflow.
Well, with stack overflow,
this happens, when the call stack just gets bigger and bigger and bigger until it just doesn't have enough
space anymore.
How can we do that?
Can we recreate a stack overflow?
Yah! I can show you quickly that to create a stack overflow,
all you have to do is function 'foo' like we have in here.
And this function will just have 'foo'.
And we're just gona run our 'foo' function, all right.
That looks confusing.
What is happening here?
This something called recursion.
And recursion means a function that calls itself.
So if you look at what this function doe, we run 'foo' and 'foo' gets executed, what 'foo' does is well, we
run 'foo' again.
So it just keeps looping over and over and over, having recursion but there is no end in sight right.
We keep adding 'foo' to the call stack.
We keep adding it, over and over and over and over and over and over and over and over.
And, we have a stack overflow.
So if you want to have fun, go to your browser, go into your console and run something like this and
see what happens.
You're gonna get a stack overflow.
All right.
So hopefully, this now makes sense.
The javascript engine which is the V-8 engine and Chrome has a memory heap and a call stack.
Now, Javascript is single threaded, only one statement is executed at a time,
but there is a problem now isn't it.
What if line two was a big big task we needed to do? maybe loop through an array that had millions of
items, what would happen there?
Well, we would have this console log execute then the second line then it is a massive massive job,
well just work there and console log '3'
will take a really long time to get loggged.
And in our small example that doesn't mean much but if he had this on a Web site well, the user wouldn't
be able to do anything.
The web site would pretty much freeze until that task is done and the user just waits there.
That's not very good, is it?
Well with synchronous task, if we have one function that takes up a lot of time, it's going to hold up
the line.
Imagine a buffet restaurant, right,
if all the people want to eat but Bobby says hold on guys,
have to keep eating and put a bacon on my plate.
Well everybody has to wait in line.
So it sounds like we need something nonblocking. Remember our first statement that we made in this video.
Javascript as a single threaded language that can be nonblocking.
Ideally we don't wait around for things that take time.
So how do we do this.
Well, asynchronous to the rescue.
Think of asynchronous like a behavior. Synchronous execution is great because it's predictable.
We know what happens first then what happens next.
What happens third.
But it can get slow.
So when we have to do things like image processing or making requests over the network like API calls,
and don't worry we're going to talk about this in future videos.
We need something more than just synchronous tasks, right.
So you're thinking to yourself, Andre How do we do asynchronous programming then?
Well, let me remove some of this clutter.
We can do asynchronous programming by doing something like this 'setTimeout', which we're going to talk
about, is a function that comes within our browsers, and it allows us to create a timeout. And we can just
give it the first parameter is the function that we want to run.
And then the second parameter is how many seconds we want to wait.
So let's say I want to wait two seconds.
So 200, 2000 milliseconds.
If I do this now, let's run it to the console and see what happens.
Well, what just happened? we have console log '1' then console log '3' and then console log '2',
two seconds later.
It looks like we just skipped this whole step and then put this at the very end.
Well, you've just witness asynchronous programming. In order to understand this and what just happened.
I need to take you to the next part and that is, in order for javascript as we know it, to run for the
javascript engine with memory heap and call stack to run,
we need more than just the javascript engine, we need what we call a javascript runtime environment. And
Javascript runtime environment is again part of the browser, its included in the browsers.
They have extra things, on top of the engine,
they have something called the web APIs, callback queue and an event loop.
And as you can see here, 'setTimeout' is part of the web API.
Its not technically part of javascript, is it?
Its what the browsers give us to use, so we can do asynchronous program.
OK.
So looking at this diagram,
lets see if we can figure out what our code was doing.
We can create here our own call stack, will have web API and then we'll have a callback queue and then
a event loop, just like we have in our javascript runtime environment.
So what's happening here?
Well, first we have console log that goes into the call stack.
And that gets run.
So we log console log '2' to the browser.
We then get 'setTimeout'
into our call stack because we finished this first task, we're going to the second one. And with
'setTimeout', what's going to happen is, well the call stack is going to say, OK, I have 'setTimeout'.
And because setTimeout is not part of javascript but part of the web API, it has this special characteristic
what's going to happen is, it triggers the web API.
And says, hey! 'setTimeout' has just been called. And because we notified web API, we can pop it out
of the call stack.
Now, the web API starts with a timer here, a timer of two seconds.
It's going to know that in two seconds, you have to do something. And because the call stack is empty,
the javascript engine now goes to console log '3' and executes this.
So that makes sense, right.
Now we've done '1' and '3' but we still have 'setTimeout'
2 seconds in the web API.
Now after two seconds when our time limit is up, the web API is going to say,
okay, 'setTimeout' should be run.
Let's see what's inside of it.
Well we have a console log 2.
So what's going to happen is, it's going to say, hey! set time is done.
We have a callback, and this callback of 'setTimeout', we added to the callback que, saying that, hey! we
have to run something we're ready to run it.
Now, the last part, the eventloop, the eventloop over here checks and says, hey! is the call stack empty,
and it keeps checking all the time.
If the stack is empty and if the call stack is empty and there's nothing running right now the javascript
engine, it's going to say, hey! do we have any callbacks?
It's going to check the callback que and say, hmm! is anything in there?, because the call stack is empty,
we can throw something in there and make it do some work.
In our case we say, oh yeah! I do.
Let me put this into the call stack.
So now we move the callback into the call stack and then the callback we run it and by running we see
that we have console log 2.
So it's going say console dot log 2, it's going to run this function and once it's done it's going to
pop it out of the call stack.
And again we're done with the callback, so we remove it, and there you go.
We're done.
Everything is empty and we've just run this '1', '3'.
It's going to go through the entire web API callback que event loop.
And then it's going to run console log '2'. Hoo!.
That was a lot of information.
So you might need to watch that a few times but hopefully that makes sense to you of why we noticed
this behavior.
And I want to challenge your understanding here.
Knowing what you know and what I just taught you what happens if I change this to zero?
That means zero second(s).
I'm going to give you a second to think about what will happen.
And then we're going to try this out.
When I clear the console, copy and paste this and run it. Well one, three and two.
Did you guessed right?
Now think about why that happened?
Even though this is zero second(s), it still went through the process.
It still got entered into the web APIs,
and then the callback queue and then the event loop.
And by the time that was happening the call stack had already moved on to the console log '3' and
only after console log '3' was done and the call stack was empty the event loop said, oh yeah! we can call console log '2'.
Hopefully that makes sense for you.
And if you're able to understand that you'll actually have a lot of people that hire for javascript
roles ask questions like this on an interview, and you have to explain why that is.
So I hope that made sense to you and you can use that to your advantage of the next century.
So let's recap.
If you wanted to load your latest tweets onto a web page and you do this synchronously, then visitors
to your site won't be able to do anything until those tweets are loaded.
This could cause a long delay before they even get to see the content of his site.
They may not be able to click anywhere and the page will feel like it's frozen.
Not a very good user experience, is it?
Another way to think about this is calling your teacher with a question.
Synchronous way is you called the teacher,
you wait on the phone until the teacher answers the phone and ask him the question and hopefully get
an answer.
So you let the phone ring until he picks up.
But you're not doing anything else in the mean time.
Asynchronous means that you send a text to a teacher with a question.
And then when the teacher, he or she has the time, will respond to you and call you with the answer.
So you can do other stuff in between. The javascript is asynchronous when you can leave it a message
and a callback tells you, hey! Mr. teacher has a message for you when you're not too busy.
And that's why we call it a callback function
and a callback que. We're calling back to let her know that hey there's some stuff waiting for you.
Now, we see over here that we have DOM, Ajax and Timeout. And there's a few other things but you also see in
the callback que, we have on click on load on done.
Do you remember the event listeners?
Well, with an event listener, we had something like an element, and we added event listener.
And in this eventlistener, we could say listen for a click and it'll have a function that perhaps just
console dot log 'click'
Well, similar to an asynchronous way of programming, we've created this 'click' function and now we're
just listening to it.
And every time a click happens on the web page.
So on the DOM,
well we run the callback function, which console logs 'click'.
All right.
So to finish things up, when is asynchronous happening? it happens a lot, when you try and talk between
machines, like speaking to a database making network requests,
image processing, reading files and don't worry, we'll go through this in future videos.
But to recap what we just learned, Javascript is a single threaded language that can be nonblocking.
It has one call stack and it does one thing at a time. In order to not block the single thread,
it can be asynchronous with callback functions and these callback functions gets run in the background, through
the callback queue and then the event loop, to bring it back to the call stack.
So next time you get asked, what is the difference between a synchronous or asynchronous program?
Or how does javascript work?
You should have a little bit more confidence to answer that question.
And I hope that this was helpful.
I'll see you in the next video. Buh-Bye.