How Does Javascript Work? - Andrei Neagoie

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] how does JavaScript actually work imagine getting this question during an interview or how about this explain the difference between asynchronous and synchronous and JavaScript or maybe they ask you to explain the statement javascript is 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 a 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 not know this it's like being a pilot and not knowing how an airplane can fly okay 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 read and run commands okay now we also know that from our previous discussion there's the JavaScript engine that each browser implements in chrome is the v8 and the v8 engine reads the JavaScript that we write in 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 I mean I have sublime text over here and for us to allocate memory and the memory heap well it's as simple as doing const a equals two one we've just allocated memory now when we assign this the javascript engine is going to remember that oh yeah a has a value of one 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 hundred and maybe here will be ten cool now what's an issue that we see with this there's something called a memory leak that you're gonna 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 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 not using the variable a but it's Gobert 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 if 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 will go one console.log two and then finally console.log three if I run this code in my browser terminal well I get one two three so the coal stack if you remember that's what reads and execute our scripts so what the call stack does it reads the first line console dot log it gets put in this call stack so the JavaScript engine says console dialogue has been added let's pop it onto this call stack and then it runs it and creates one then it says okay I'm removing the first console lock because I just finished running it I'm gonna place the second console log into my call stack adds it on here and says yep execute - and then it removes that it pops it and then gets console log three and logs console log three 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 calls to and for now it's not I'm really gonna do much is gonna console dot log for and then in here we'll just say we run the to function so if I copy and paste this and place it into our console and I run one I get four and ignore this error here it just related to my app in the browser but you see that we get four 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 four that's run inside of the to function so now that we've read this the call stack is going to say okay there's nothing else inside of this I'm going to run console.log for so it's gonna print out number four 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 non-blocking single threaded means that it has only one call stack and one call stack only it 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 of the call stack gets run first then below that below that below that until the call stack is empty now other languages can have multiple call stacks and these are called multi thread 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 design 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 multi-threaded environment you just have one thing to worry about and when I say issues we'll with multi-threaded environment can have such thing as dead locks 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 about to 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 step 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 coal stacks 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 yeah 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 food and we're just gonna run our flu function alright that looks confusing what is happening here this is something called recursion and recursion means a function that calls itself so if you look at what this function does we run foo and foo gets executed what foo hat does is well we run through again so it just keeps looping over and over and over having a recursion but there's 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 into your browser go into your console and run something like this and see what happens you're gonna get a stack overflow alright so hopefully this now makes sense the JavaScript engine which is the v8 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 2 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 that is a massive massive job will just work there and console log 3 will take a really long time to get locked and in our small example that doesn't mean much but if you had this on a website well the user wouldn't be able to do anything the website 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 tasks 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 I have to keep eating and putting bacon on my plate well everybody has to wait in line so sounds like we need something non blocking remember our first statement that we made in this video javascript is a single-threaded language that can be non-blocking 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 is 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 all right so you're thinking to yourself Andre how do we do asynchronous programming that well let me remove some of this clutter we can do asynchronous programming by doing something like this set timeout 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 minutes 2,000 milliseconds if I do this now let's run into the console and see what happens you well what just happened we have console.log one then console.log 3 and then console.log 2 2 seconds later it looks like we just skipped this whole step and then put this at the very end well you've just witnessed 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 it's included in the browser's they have extra things on top of the engine they have something called web api's callback queue and an event loop and as you can see here set timeout is part of the web api it's not technically part of javascript is it it's what the browser's give us to use so we can do asynchronous program okay so looking at this diagram let's see if we can figure out what our code was doing we can create here our own call stack we'll have web api and then we'll have a callback queue and an fan 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 to the browser we then get set timeout into our call stack because we finish this first task we're going to the second one and what set timeout what's gonna happen is well if the call stack is gonna say okay a half set timeout and because set timeout is not part of JavaScript but part of the Web API it has this special characteristic what's gonna happen is it triggers the web api and says hey that timeout has just been caught and because we notified away baby I we can pop it out of the call stack now the web api starts a timer here a timer of two seconds but it's gonna 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 set timeout to seconds in the web api now after 2 seconds when our time limit is up the web api is gonna say ok set timeout should be run let's see what's inside of it well we have console.log - so what's going to happen is it's going to say hey set timeout is done we have a callback and this callback of settimeout we added to the callback queue saying that hey we have to run something we're ready to run it now the last part the event slip the event loop 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 on the JavaScript engine it's going to say hey do we have any callbacks it's gonna check the callback queue 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 sack 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 - so it's going to say console dot log - 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 one three it's gonna go through the entire web api callback queue event loop and then it's gonna run console of log to prove 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 seconds I'm going to give you a second to think about what will happen and then we're going to try this out I'm gonna clear the console copy and paste this and run it well one three and two did you guess right now think about why that happened even though this is zero seconds it still went through the process it still got entered into the web api's and then the callback queue and then they event loop and but the time that was happening the call stack had already moved on to the console.log three and only after console.log three was done and the call stack was empty the event loop said oh yeah we can call console.log too 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 makes sense to you and you can use that to your advantage of the next interview so let's recap if you wanted to load your latest tweets onto a webpage 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 your site they may not be able to click anywhere and the page will feel like it's frozen not a very good user experiences another way to think about this is calling your teacher with a question synchronous way is you call 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 meantime asynchronous means 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 so javascript is asynchronous when you can leave it a message and a call back 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 in a callback queue we're calling back to let them 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 queue 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 middlemist nerve we could say listen for a click and it will have a function that perhaps just console.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 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 non-blocking 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 into the call stack so next time you get asks 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 did you enjoy the video I make a living creating content like this for developers you check out the resources I talked about in the video in the description down below also I teach people how to go from zero knowledge to mastery as developers in a single course check out the link below for the course introduction and some free video content to see if this is something that you want as part of the course we have a community of people just like you thousands of them talking in our online slack channel hope to see you in there one day
Info
Channel: Udemy Tech
Views: 48,429
Rating: 4.9349971 out of 5
Keywords: how does javascript work, javascript, javascript engine, event loop, JS, JavaScript (Programming Language), asynchronous, synchronous, single-threaded, non-blocking, callback, single threaded, call stack, heap, web api, web developer, learn to code, learn javascript, JSConf
Id: hGSHfObcVf4
Channel Id: undefined
Length: 24min 52sec (1492 seconds)
Published: Mon May 07 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.