SPEAKER_02

Welcome to the React show. So, what does the browser actually do when you add two numbers together and assign it to, say, a variable? Or, like, what does it do in general when it executes your JavaScript code? How does the event queue work? Does React take advantage of any browser optimizations? We're going to jump into the inner workings of your browser today and learn how it all works. You were born a social animal in a world that was meant to be less measured, less exact. And now you sit with dancing photons blasting away your eyes as your muscles atrophy and your social skills lapse. In a world where everything is measured and exact. You emerge from your cave that you call an office to find yourself torn away by the currents of the journey. Of the journey we are all bound together. Whether you're just learning to write code, or you're a 50-year expert that knows APL just as well as TypeScript, we're all on the same journey together. So join us on the React Show as we explore how to make better programs, better teams, better companies, and a better world together. The React Show is a weekly podcast brought to you from occupied Miwak and Pohatan Territory, focused on learning more about React, programming in general, and the intersection of programming and the rest of the world. Come join us on this journey. Thank you for joining us on episode 43. Allergies, maladies, I really can't sing. But yeah, it's that time of year, and I'm not Paul Simon, but Austin and I both have allergies. But how about you, Austin?

SPEAKER_00

Yeah, dude. We were just in San Francisco last week on some work stuff, and my allergies were completely gone. And then I came back on Friday, and within 30 minutes of being in the airport, I was like doubled over, like sneezing and coughing, and like my nose has been running since I I get like maybe 30 minutes to an hour a day of clarity where I'm like I can breathe and then it's gone. Um yeah.

SPEAKER_02

I I totally know what that's like. Yeah. Oh, that sucks though.

SPEAKER_00

I hate having to take medicine like ever, and I'm like taking Zertech every day, and it's really like one of the only things that really helps, and I'm like, oh my dependency, my weakness.

SPEAKER_02

Oh no. Well, it is a weakness, or maybe it's not. I I don't know. I think it's debatable. But either way, what's not debatable is that we're with Owl Creek, an organization focused on React, React education, and today JavaScript in general. So yeah, I'm excited. Um and like always, I'm your co-host. Uh I'm your co-host, I'm my own co-host, I'm your host Thomas with my co-host Austin. Welcome to the show, Austin.

SPEAKER_00

Hey, thanks for having me back.

SPEAKER_02

Did you want to be the host of my co-host?

SPEAKER_00

Uh not today. I I'm looking forward to uh grilling you with questions versus last time getting grilled.

SPEAKER_02

Well, you know, we all need to get grilled from time to time. It keeps us charred.

SPEAKER_00

Right. I like it crispy.

SPEAKER_02

Crispy, yeah, yeah, me too. Um, yeah. Uh and if you haven't already and and you like uh listening, don't forget to subscribe, rate, and comment this podcast. It it does help us continue to bring shows like this to you every week and bad jokes and and bad singing. So if that's your kind of thing. Um, but yeah, I I'm excited to get into uh JavaScript itself. Um, you know, how does it actually execute in your browser? And you know, I think this might be a topic where some or maybe a lot of people sort of tune out because it's like, I don't really why do I care how it executes? I just write the code. All I care is if my code works. Well, my experience is the more you know about how things work underneath, the better you will be at making them work on top. Um, and especially if there's um bugs you're trying to track down or performance bottlenecks. Just having a general idea of how it works can be super, super beneficial and save you a ton of time. Um, and so like I might say a lot of jargon today. I'm gonna try to keep that as minimal as possible. I'm gonna try to keep it as light as possible. But the intent is not that you memorize everything I say, but just to like try to start forming a mental model of like what's going on, because I think that can help a lot. Um, and I think it also helps, you know, when we talk about React, because um what I think is fascinating is we can stuff we've talked about before with React, we can see how they've utilized some optimizations and some of the way that um react uh JavaScript works in the browser to make React faster. And that influences the design of React itself, I believe. And so it all, you know, it all kind of neatly ties together. Um yeah, so uh let's start with the very beginning, right? Your JavaScript code gets sent to somebody's browser or a a client, right? We'll we'll say a browser. Um and it and note that we're sending the the code itself. Like, you know, you can inspect the code, right? Like we all know that we're we're web programmers, but that's actually somewhat unique. Think of like most programs. Like, like if you download a program off the internet or an app from the app store, whatever, you can't inspect that code, it's already been compiled. So the web is somewhat unique in that we just literally send the source code, and to me, that's pretty awesome. I think you know it has its disadvantages, but I think it's pretty cool. Um, I don't know. Have you ever thought much about that, Austin?

SPEAKER_00

I'm thinking back to like one of my 101 classes when I was in college talking about the like how things go up and down that tree of communication. The what what are all those layers? There's like eight of them, like down to the like there's the application layer and it goes down to Oh, you mean like all the way down to executing on the CPU? Yeah, exactly.

SPEAKER_02

Yeah, I have no idea what the the eight layers are, but there's a lot of layers.

SPEAKER_00

Well, I was just thinking how like JavaScript it's it starts at a higher layer and has to traverse that tree up and back to output where like yeah, these these compiled programs only really have to go up. Yeah. Um and so it's definitely at at a disadvantage from the start, but I mean it's pretty cool how yeah, literally you you point to a script file at some domain and it's it can run. It's just there.

SPEAKER_02

Yeah, and I I'm actually all right, so you said it's at a disadvantage to to start with, and in some ways that's true. But what I think is actually really cool about it is in other ways that's a a positive because that means browser, you know, the people that make browsers can do anything. Like, like if you send pre-compiled code, there's you can't do near like that much with it in terms of um optimizing it further potentially or letting you step through the code to debug it in the in the browser, whatever. Like it it definitely is a disadvantage. Um, and we're gonna we'll we'll talk about like some of the tech technical parts of that, but I think it also, I don't know, adds some cool stuff too, you know.

SPEAKER_00

Yeah, I mean compare, I mean you have extensive experience with like debugging, compiling uh with what you've written in the past. Um I mean you're kind of given like a cheat code there with the browser. It is like it is live debugging, and I mean each website, even stuff in production, you're you're able to look into their source code to some degree uh and like live debug or examine and expect. That's it's definitely a completely different paradigm versus doing that with compiled applications. Like you can how how easy is it to take like a compiled application and like r revert it back to its source, like breaking the source code out of it. Like you can't even do that very effectively with anything.

SPEAKER_02

Yeah, exactly. So if you take compiled code um that hasn't had extra stuff done to it to make it like include source code, you you cannot go back to the original source code. The compilation steps, most of them are you know irreversible.

SPEAKER_00

Right. Yeah, so it's like a completely different, like you'll never be able to interact with any of these applications you use day to day, but with web applications, every one of them you can learn from.

SPEAKER_02

Yeah, I think that's so cool. And um we can we can go on about that, but I think it it ties in really well to um what I wanted to get into next is like what actually happens when that JavaScript code gets sent to your browser. Like, what is the first thing your browser does? Um, and that would be parsing. So when your browser gets JavaScript code, it's it's just like text, it's it's a string, it's basically one gigantic string. That's what it technically is, right? Um, and the computer doesn't know anything about it, doesn't know what to do with it. Um, it has to start analyzing it to break it down into something it can work with, right? So that's called parsing. And in there's um programs that are are parsers and there's parser generators and stuff. You don't have to worry about that. Um, the easy way to think of it is just like a parser is something that like uses, for example, a regular expression to extract um tokens from your source code. So like let's I'm gonna go to this example a lot. So let's say you're you have the constant x equals one plus two. Like that's the code we're trying to execute. The browser, when it first gets that, it doesn't know const x, it doesn't know any of that. It's just a string with that stuff in it, right? So let's say you create a regular expression that recognizes the const keyword, you know, followed by a space or something. Well, you know, now we're we're starting to run a parser and we can start to understand what this code is. And so that's the parsing step. We're extracting these tokens from the source code. And so um, the first step is your browser runs the the parser over your source code and starts to understand what things are. So it might say const and be like, oh, this is a constant variable declaration and attach that meta information to those characters in the string per se. Or it can build a tree or different data structure, but it starts to recognize that, right? Or it gets to the number one and it's like, oh, I see a number and it's you know surrounded by other tokens, so I can make that a number and maybe it even converts it to a number, you know, who knows? It might leave it as a string. But basically, the idea is it starts to break up your source code into these tokens, but that doesn't mean it knows what to do with those tokens. That's we'll talk about that in the next step. So the first step is parsing, and there's two distinctions here. So in the browser, we have an eager parse and a lazy parse. So think about this. Uh, you send a source code with like a function definition in it, right? Well, the browser might be like, you know what, I don't I don't think I'm I don't think I'm gonna need to run this function right away. So it might just not even parse it. It's just like, hey, this is the start of a function declaration. I'm just gonna look for the end of it and skip everything in between, you know? Like it can and it will do this. Uh so you could do a uh an eager full parse where it literally parses out everything, or it can do a lazy parse, which is just the bare minimum it needs to start being able to execute code. Um, and you might be thinking, like, why would you do that? Or you might be thinking, oh, that's obvious. Um, but we are very fortunate, and we have Austin here who can tell us why we would have eager or lazy parsing.

SPEAKER_00

Well, I'm just looking at my I I know like Thomas, you like your Linux and I have a Mac. But I'm just like looking at this this thing right now, and it's amazing to me that we're talking about like, okay, so I'm looking at the show notes right now and this website has parsed this code and is now displaying all of this to me. But that's like part of this like insanely large amount of operations going on from top to bottom, and the fact that we can like even display websites inside of this uh circuit board and display and stuff just was like blowing my mind. Um it's pretty crazy, but every every part that does from top to bottom is explainable down to this uh detail of like where we're talking about parsing eagerly or lazy, right? Yeah. Um so I guess you could say easy eager parsing would be it would allow it maybe a slower startup, right? But it would cache your code in some way, or lazy would be kind of like as needed just in time, it'll load in for performance mainly, right?

SPEAKER_02

Yep, exactly. So eager if you do an eager parse, um you're gonna be able to run code quicker later on. Um, but if you do a lazy parse, you can rot run code quicker right away. Um and uh you know, I don't actually know the browser strategies, but my guess would be they would tend towards a lazy parse for whatever the initial JavaScript is they get because they know the user just wants to see it working, you know, even if it's a little bit slower. Um and then later on maybe it switches to uh an eager parse. Um but yeah, that's that's parsing. There's that's a whole topic you can dive really deep into. We're just gonna I'm just gonna explain what it is here, and uh we'll move on to uh the next thing, which is the AST. So uh a parser actually generates generally a data structure called an abstract syntax tree. Um and we we don't have to go too far into other than to just imagine a tree, and I'll like take our previous example of like const x equals one plus two and sort of explain what that would look like in an abstract syntax tree. So uh in that example, the top of the tree would be the um like uh what do they call it? Like uh I I don't know if I remember the name.

SPEAKER_00

Like an identifier?

SPEAKER_02

Yeah, so in this case, uh equals would be not an identifier, um, that would be like X. Uh so I'm thinking, so at the top um would be a I can't remember the name of it. And I had uh I totally had uh example. Oh, here we go. Oh yeah. So so that would be at least in general, that would be like your declaration. So the declaration would be at the top, and that would be uh you kind of think of that as like your equal sign. And to the left of that, you could have your identifier, which is X, you know, and to the right of that would be an expression. So that's how so the computer's like, oh, I know that if I have a declaration on one side, I have an identifier, and the other side I have an expression. That's how it always works, right? So on the expression side, on the right side, we're gonna have another tree, and the top of that would be uh uh an identifier. I guess so I mean it depends on what you call identifier. I guess you could call plus an identifier as well. But yeah, so uh plus would be like an identifier. Um yeah, sorry, I'm not yeah, okay, in JavaScript, I guess we could call plus an identifier. Yeah. Anyways, don't don't worry about the uh the technicalities there. Just know that, like, just think of it as like plus as being there, and then to the right and left of it would be one and two, you know, the numbers, right? Like the the technicalities of the names on this don't matter. Like we'd call uh we call like um one a literal and two a literal, like they're literally like they don't do anything, they're just literally there. So, anyways, that's our tree, right? Um, and you're like, okay, whatever, like why would I want this tree? Well, think about it this way. If you were to like execute this program like in your head, like you're just gonna start executing it, how would you do that? If you if you like write this out on paper or something, you'll see that you would follow this tree. And that's why we do it. Because we start at the top of the tree and go, okay, what do I do first? And so so uh this is like uh the AST that's the data structure. Now we're talking about um this is actually how interpreters work. They would take this data structure that we created from our parser and start the top of the tree and start interpreting. And so uh it would see that like um declaration, and it would be like, oh, okay, I need to store something. What do I need to store? I need to store uh this expression. So it's gonna go to that side of the tree and it's gonna be like, oh, well, I don't have a value to store yet. I have another part of the tree. And so it's like, okay, what do I do now? Oh, it's an expression, and I need to add things together. Well, that means on the right and the left side, I'm gonna have either a literal or an expression, and it finds a literal, and so it's like, okay, I will pull those literals up and say, okay, how do I add things together? And then an interpreter will just add them together, and so you'll have three. And now you can think of that tree as being made up of the number three instead of that subtree that had the plus one two, and then it goes back up the tree again and it's like, ah, okay, what do I do now? Oh, I have a value on one side and I have my you know uh identifier that the X on the other side. I need to just somewhere in my memory say that X equals the value three. There we go. We've just interpreted a program. Does that make sense make any sense, Austin?

SPEAKER_00

Yeah, I was like visualizing it, and it was like I saw this tree and I saw like electricity go down it, and like it as these answers came back from the interpretation, it like shot back up and to the the root. I don't know. Yeah, exactly. But yeah, so looping back to the AST stuff, like on a practical term, I remember my friend was asking me something about he he was pretty new to programming and he was asking about like how does Babbel work? And Babbel is pretty much before you uh compile this ECMA 6 uh ECMA script six plus whatever uh code with these other transpilers, you're actually doing AST uh data structure alterations or custom ones, right? Yep. And so then these are eventually even like that's why you can't just write some of these things in directly in the browser without compiling it into that, but then the browsers are also then like ad adapting and putting these things directly in their own compilers, uh, correct?

SPEAKER_02

Yeah, so Babbel is is a transpiler, basically it's effectively a compiler, and it needs to do the parsing and the AST generation. Just like the browser does. So yeah, you're absolutely right.

SPEAKER_00

So when something transpiles, that is like translation and compilation in one. So I'm just like these two tactical things.

SPEAKER_02

No, so the difference is um like yeah, so it is basically like a compilation step. So like you know how here we did this like exercise where we interpreted the AST?

unknown

Right.

SPEAKER_02

Babel is not necessarily gonna interpret it, it's gonna take that AST and generate new code from it, like new JavaScript code. Yeah, so you're right, it's essentially a compiler.

SPEAKER_00

Right, okay. Yeah, I just remembered this. My friend asked about that, and it was in we had like we had a list of like eight eight QA things. Uh we've checked one off now, right?

SPEAKER_02

Yeah, yeah. The that that's a I didn't even think about that, but I'm glad you brought it up because JSX is is another language that is not JavaScript, and to and and that's what Babbel and and things like that are doing is taking that non-JavaScript code, building up an AST, and then outputting JavaScript. And the way it does that is just by walking that tree like that interpreter did. I mean, and it might do some other stuff, but like essentially that same thing, but just outputting something different. It's pretty cool, right?

SPEAKER_00

Yeah, and I love all these little uh like the spread operators and all these other things that have come out of Babel, uh, or future future translations. Uh yeah. I mean, I think look forward to what's to come.

SPEAKER_02

Technically, that might have actually been part of ECMA script, but like not available in the browsers yet. Because like, so that's okay, that's a really great point. So going back to the very beginning of this, the browsers have to parse this code, right? So, what if you send it code from a newer version of JavaScript it doesn't understand? How it won't know how to parse it, and that's why we have Babbel converting our newer JavaScript code to older JavaScript code, right?

SPEAKER_00

Right. Yeah, um, we had a problem with that recently. Well, a few months back in uh in older times. That uh what was the double question mark up mark operator called?

SPEAKER_02

Oh, like nullish or whatever.

SPEAKER_00

Yeah, I like that one.

SPEAKER_02

Yeah, yeah. So that's exactly it. If you use something that the browsers don't understand, it this is where it chokes. It chart chokes at the parsing. Or I mean it could choke choke at AST, but probably it chokes at parsing, you know. Um, it's it's like I don't I don't know. Uh sorry, it wouldn't choke at AST, it's a data structure, but when it gets to the steps after that, and um yeah, I I agree. So I think that's really cool. Um, I wanted to say a little bit more about the interpreter. So something you'll often hear about is bytecode. So you might be like, what is bytecode? Well, you know this um example we went through, it's like that AST is storing um, you know, long bits of strings that it basically pulled out of your source code. Well, that's um not very efficient, and it's also not very efficient for interpreters to execute. So when you see bytecode, um usually that is taking that AST that we generated from the parsing step and doing like a uh another pass on it to convert it to something that is more efficient for uh computers to execute. So like um think of it this way that like um plus, you know, uh when we're adding things together, um, you know, that could be made into like a jump in in memory when you're like when we're talking really low level, like assembly level, like really low level or whatever. Like that can be like just a jump into a specific place or something. So you're not having to be like, oh, what is this? Oh, it's a plus. Oh, it's you know, whatever. Instead, it's just I'm gonna jump straight there. So it's kind of like I'm sort of going uh really high level, but just when you hear bytecode, basically just know that means it's like a more efficient way to store your abstract syntax tree for the interpreter to execute. Does that make sense, Austin?

SPEAKER_00

So pretty much the browsers like I got a dictionary of like free of these symbols or whatever tokens.

SPEAKER_02

Exactly, yeah.

SPEAKER_00

In the then it matches it with the computers just to use their cache instead, right?

SPEAKER_02

Yeah, it's kind of like that. Yeah. Um and it it can be uh, you know, Java. So Java is always compiled to bytecode, and you distribute the bytecode, not the Java code. And there's so there's other reasons for this. Bytecode is a lot more compact, it's like a compressed program, you know. Um but it can also be bytecode can be generic. So your uh like Mac CPU, like the one that Austin has on his M1 computer, you know, this M1 ARM chip. I have an X8664 CPU on my Linux system. They can't run the same machine code, they don't speak the same language. And bytecode can be written generic so it runs on both systems without having to like do a whole bunch of extra work. So that's another reason why you might see bytecode being used. And we're gonna talk about how it gets used in the browser later on. I just wanted to mention it now so that we can refer back to that later on. Um, but now we'll talk about compilation because browsers also do compilation. So, what is compilation? Compilation again starts with that abstract syntax tree data structure, but then it starts doing optimizations. So let's go to our example uh const x equals one plus two. Are there any uh I'm I'm curious, Austin, do you do you know of any uh uh optimizations we could do on that statement?

SPEAKER_00

Well, I mean, I already know one, like there are two literals, why not just pre-combine them with my human brain and just say const x equals three, right? Exactly. Calculate that.

SPEAKER_02

Yeah, so that is one of the steps a compiler might take. It might see that and go, oh, I can just add these two literals right now and replace it. Or it can even go further. Think about this. If x is a constant, why do I even need x? I could just put three everywhere that I see x, you know, right? So so this is all really that's all the the compiler's optimizations are is basically going through that abstract syntax tree and looking for patterns and stuff like that and transforming them into more efficient things. And so it will usually start with that AST and do multiple passes on it, and you'll end up with like a totally different AST that still produces the same output, like it's still your program, but it's a lot more efficient. And so, uh, and then the other part of a compiler is compilers normally output um, and and we were talking about this earlier. So compilers can go from like JSX to JavaScript. They don't necessarily have to output machine code, but in a browser, usually your compiler will take this abstract syntax tree and in the final step actually output machine code that just runs directly on your CPU. And obviously, that's gonna be faster in most cases than the interpreter that has to like literally interpret things over and like over and over again and doesn't have these optimizations, right? Um does that make sense?

SPEAKER_00

Yeah, and uh and something that came up um while you're talking about like X being replaced by three then during this optimization step, uh, that's why like defining global variables or changing things like that you shouldn't be changing in places, because the optimizer will go through and potentially wreck everything, right?

SPEAKER_02

I mean what will happen is the optimizer will say, I can't be run on this code because it is doing weird stuff, and so it just doesn't get optimized. Okay, that's good then. So it depends. There are ones where it will optimize it, but it will have a check. So it'll be like, hey, if this has changed, then disregard my optimization and like recompile or something. So you can go either way, but yeah. So that's the super short version of uh parsing and interpreting and compilation. Um, if you guys found that interesting, you know, definitely let me know. I love that topic and I I know a fair amount about it, or you could just, you know, look it up. It's a lot of fun, it's really easy to build. Like uh for some languages, it's super easy to build interpreters and it just feels so cool. Like when you get that working, you're like, yes, I am a computer. But but yeah, so so once once you are a computer, then you can move on to the next um subject, which is even more difficult, but we'll we'll work our way through it, and that is threads. So just so so Austin, let me ask you this. Now that you're a computer, how many how many threads does your code get executed on in the browser?

SPEAKER_00

In the browser, there's just one available, correct?

SPEAKER_02

Sort of. This is where it gets interesting. So your code.

SPEAKER_00

You're not allowed to ask me trick questions, man.

SPEAKER_02

That's the whole point. Because I should everyone else is thinking the same thing. And then they're like, yeah, Austin. And then I can be like, no, just kidding. No, actually, you're so conceptually, conceptually, you're right. Your code that you wrote and sent to the browser is only running on one thread at a time. Now, where it gets more interesting is the browser, I think originally, we'll we'll get into the history here in a little bit, but like originally that is how it worked. There was one, in fact, there was one thread for your entire browser. All the tabs, everything had I don't know if you remember those days, like 20 years ago, when if one site like locked up, literally your entire browser just was done.

SPEAKER_00

Like that was yeah, definitely, definitely remember. It was very early in my years, though.

SPEAKER_02

Yeah, so now um it it depends. Like, if you're like Chrome and Firefox are a little bit different in this way, but Chrome is like, I'm gonna give a new process to every tab. And within that tab, there can be multiple threads. Um, I believe Firefox still just has like one process but tons of threads. That is not really as relevant. The thing that matters is you have one main execution thread that your code runs on, but the browser makers were like, wow, this is like horribly inefficient on multi-core CPUs because um what if we get a network request? Like, can't we like kind of process it? What if uh there's painting and rendering and like oh what about this? What if you like your application is running and then uh you are using um fancy new React features that let you send code you know from the browser to your or from your server to the browser after it's running, right? The may what if the browser was like, hey, you know what? I could parse and compile this script while the code is being run, while I'm running the user's code. Like maybe that works, you know? It might be just parsing, I don't know exactly how much it can get away with, but like there's a lot of stuff that the browser could be doing while your code is running. And so, yes, while your code can only run on uh uh one main thread at a time, it it is uh the browser actually has a bunch of other threads in the background that are sort of orchestrating things and getting everything ready for your bits of code to run, basically.

SPEAKER_00

I was just thinking about yeah, we can listen to YouTube in the background as well, right?

SPEAKER_02

Yeah, yeah.

SPEAKER_00

And I wouldn't be able to be talking to you over the the podcast right now via Jitsi, right?

SPEAKER_02

No, so so that's not uh entirely true because think about this. If you had one thread, but everybody got a slice of it, then then it would work fine. Um like that's how it generally worked.

SPEAKER_00

Yeah, so threads are like pies? Yeah. But long long pies.

SPEAKER_02

Long pies, yes. That's it.

SPEAKER_00

Well, I mean, threads don't have to be long.

SPEAKER_02

No, they don't. They could be really short.

SPEAKER_00

So why are they threads then? Is it just really pies?

SPEAKER_02

Well, I think they use thread because it's like an execution thread. You like go one statement, one statement, one statement, but yeah.

SPEAKER_01

Right, right.

SPEAKER_02

No, I like it. So, yeah, so the thing to know is that your browser does have a bunch of threads, but your code can only be running on one thread at a time. Um, and the reason for that is actually more around the memory model of JavaScript. JavaScript doesn't, um, unless you're like using web workers, but like on the main thread, um everything assumes it's working in this fashion where your code is only running uh on one thread at a time. And that has a lot of implications because like think about this. What if your JavaScript code was running on two threads at a time and you told the browser DOM to update in two different threads at the same time? Now the browser itself would like need to have need to be programmed for that so that one didn't overwrite the other or something like that. And so basically, because historically JavaScript ran on one thread, all of the APIs and the browser internals and the entire memory model and the way JavaScript programs are written is under that assumption. So even if technically it like technically it would be trivial to run your code on eight different threads at once, like if it's just JavaScript code. But if you're trying to interact with the world in any way, you're gonna have really weird stuff happening. It's probably gonna, I mean, probably gonna crash, but like, yeah. So that's that's um the the thread. There's also um I should mention the event queue, which I'm sure everyone has probably heard of at this point. Um, but that's the way that we basically control what gets run on that one main execution thread. So going back to our network request, let's say you um made uh you like uh made a network request to the server, you like push put on the data something or put some data on the server and you were waiting for some data to come back, right? And when that data comes back, you want to run some code. We do this all the time, whether it's async or callbacks or whatever, right? Um so uh that works via the event queue. So if the browser gets that network request, it's gonna be like, oh, that's right. I remember Austin wanted to run the XYZ function on this code. I'm gonna put that in the queue. And so it's just a queue. It it uh like a first in, first out queue. So you you could queue up a bunch of these things, or like a set timeout, or if the user clicks a button, like all these events, all it does is go in this event queue. And when your code gets done running on that main execution thread, it goes and grabs the next code to run from that execution thread. So does that make sense?

SPEAKER_00

Yeah, absolutely. Uh as you were talking about this, I I thought of like on Stack Overflow, I I was looking up like how to do some function uh in JavaScript, and some guy left a a response um where he had like over 20 different functions he had written that did uh the same exact operation, like a a difference comparison or something in like 20 different versions, uh like based on like how to properly uh uh optimize how you're iterating or doing the comparison, right? Yeah. Um I just like this came to mind and so and and then how they all connect together into into this this single thread queuing up like that. Uh sorry, my my mind was kind of like playing with all this stuff.

SPEAKER_02

No, that's that's uh a great example, it's really fascinating. Um yeah, I mean that's my goal with this really is to you don't maybe have to remember all this, but like I feel like it just helps your brain, it like it's like, oh I remember that, and then it's like oh that makes sense now, or maybe that's why it's like this, you know.

SPEAKER_00

Well, I mean, it makes like everything when you see so many things in a program are fighting for this, like the spot in this queue, like how you write your code really does take on a deeper meaning, and then that that percolates up into like how you write your React. It's just like thinking about how all these layers and then how the browser like consumes what you've written after it's been worked through this whole tree of um communication layers down to executing, it's pretty wild.

SPEAKER_02

Yeah, yeah, it is. I don't I love it, I love it so much.

SPEAKER_00

And just like I think it's amazing that like all of this is happening almost like instantaneously or real time. Yeah, it's wild.

SPEAKER_02

Yeah, it's it's really fun. Um, if you ever get a chance to look at like disassemblies of compiled programs or like like how things like actually run on the CPU, that always just I love it because it's like, oh wow, that's so cool. Like it's doing this, you know, every like microsecond or whatever, you know.

SPEAKER_00

Well, yeah, when you talked about bytecode, I looked up on Wikipedia, um, and there was some like there's a Python script that you can import the disassembler, uh, and you can disassemble like uh the the text string and it shows like load name, like load const call function, return value, and it's it's quite interesting. It's just to think that that that's just your hello world example, right? And then it does that for for an entire program, but there's so much that goes into this.

SPEAKER_02

Yeah. Yep. And we're about to to get into uh an even more interesting use of it. So I'll I'll talk about the uh the history a little bit here, just because I think it helps to remember things. Um so as a lot of people probably know, JavaScript was not originally meant to be fast. It was like, hey, we have a browser and we just needed some glue to like make it so we could do some super, super, super simple stuff, right? Like nothing like we do today. So that's like what it was originally created for. But I think it was like the late 2000s. Um, and I don't know if Google Chrome was actually the one to the first one to do this, but the what I had found was that in the late 2000s, um, they had so okay, so I I sort of skipped stuff. So until that point, all the browsers just had that interpreter. So they would parse it and interpret it, right? And that is parsing and interpreting that's like easy to make, and it's you know, works, but it's it can be slow, right? Like, so that's that's the whole downside of an interpreter, is it can be very slow. Um, and so in the late 2000s, I don't know if people remember this, but like there was definitely a lot of issues around performance in in the web. I mean, we've had issues for a long time, but Google was like, hey, we're gonna Do something about this. And so they rewrote the or they basically rewrote a browser engine to use a just-in-time compiler or a JIT compiler. So before, where your code would get parsed and then interpreted, um, in the Google Chrome browser, it would get parsed and then it would get compiled. And I don't at the time, I don't think there was an interpreter. Um it was just no matter what, you sent it code, it compiled it. And a JIT compiler just means like uh just in time. So it might not compile everything up front, but as soon as it needs to run some code, like say you get a something in your event queue, uh a callback or whatever, um, it will like compile that, you know, so it can run it or whatever. So that's like your just in time compiler, but that's what it was. Um, but that as we talked about, like Austin kind of brought up earlier, is like compilation. I guess Austin brought it up with like the parsing, like eager versus lazy. You know, um, it's the same with interpreter or interpreted or compiled. Interpreted can be done very quickly. Like compilation is expensive. Like, I don't know if you've ever like sat there and compiled some like big C program or something, and you just see all these like symbols flying on the screen. You know, it's like what you see in the movies, right?

SPEAKER_00

Like, yeah, it is the it is, yeah.

SPEAKER_02

But that can take literally hours for a lot of programs, right? Um, and nobody wants to wait hours for their JavaScript code to be compiled after it gets sent to the browser. So what browsers do now, I and I don't I'm focusing mostly on Google Chrome just because it's kind of the most popular, but I think all the other ones are very similar. Um, so Google Chrome, it actually might run it interpreted at first, just so that you get instant feedback and you see it doing things. But then it has like a special bit of code that's like analyzing uh your program and noticing if there's like what it calls like um hot parts or something. So, like, let's say I have a loop that runs the same code over and over again. Google Chrome will be like, oh wow, that's just so inefficient. I'm just like interpreting the same line of code over and over and over and over again. So it'll be like, hey, I'm gonna send this to my turbofan compiler. So it sends that to the compiler, and then it gets that back. And so then it doesn't have to interpret that like code again. So it's sort of a hybrid model where sometimes it is an interpreter, sometimes it uses a compiler. Um, but yeah, that's kind of where we are today. What do you what do you think about that, Austin?

SPEAKER_00

Well, I as we went into the history of JavaScript, I wanted to go back to like the genesis of it. Um and uh do you know Brendan Ike?

SPEAKER_02

Uh not personally.

SPEAKER_00

I I didn't know his story, and I didn't know that JavaScript was created in ten days. Uh and he's gone on to become the he he's the co-founder at Mozilla and runs brave now. I I didn't know that history.

SPEAKER_02

Yep, yeah, pretty cool, huh? Ten days. Well it sounds so that sounds like uh impressive, um, which okay, I don't want to take away from its impressiveness, but if you have written an interpreter or two, you'll be sounds hacky. Yeah, I mean it could be. Uh writing interpreters, once you've done like that stuff a little bit, it you can do it in a day, depending on the language. Um, they're that simple, they're that easy. Yeah.

SPEAKER_00

And his just happened to he was in the right place at the time with the skill set to make it and have it get spread out like anyone could create uh their own language, yeah.

SPEAKER_02

Yeah, yeah. I mean, I mean, I think there's yeah, there's definitely a lot more to probably why it was able to spread like that, because people have been making their own languages for ages, you know.

SPEAKER_00

Um, but yeah, I definitely well I guess it it all was uh built upon his time at Netscape and they were I mean they what what other browser well Net was Netscape a a browser or was it like a whole OS? I or was it like one of these all in one kind of like I it was its own thing?

SPEAKER_02

I mean that's hilarious you say that because people have been saying the browser is an OS for a long time, but it was just a a browser. Netscape Navigator was a web browser.

SPEAKER_00

Um I never I don't I think I had AOL um and I think one of my neighbors had Netscape, but I I don't remember.

SPEAKER_02

I never I never used Netscape Navigator directly. Um yeah I I actually I don't know what AO what was I don't know what the AOL browser was, but yeah my parents had that and then I used I forget what it was called it wasn't Firefox at the time, it was like Phoenix or no, there's something even before that, I think, but yeah, and then of course you had IE, all the IEs that were fantastically terrible. I mean that actually that was one of the things that like I think made IE like even worse was like even though it was already bad in like the you know early 2010s or whatever they weren't like adding uh any of these things that Google Chrome and Firefox were adding with the compilation and and multiple threads and all that, you know, until like way later.

SPEAKER_00

Yeah, I was just having like reminiscence back to back to like when I got into like what would my first web development experience be, or how'd I like get in that direction and like aim profiles, you could like change the colors and stuff, and then like found like my friend like had a Tumblr blog back like when Tumblr was I don't even know, but he like showed me how he themed his with some CSS and stuff, and I was like, Oh, that's kind of cool.

SPEAKER_02

Yeah, I mean I was back on the like the Geo Cities days. Yeah, that was yeah, yeah, it's it's changed a lot since that hey. So this is a perfect segue into what happens today. So what happens today uh when your browser receives source code? Uh I'll just we'll we'll walk through the steps. So it parses it. Generally, it's gonna come bytecode compile it, regardless of interpreter or compiler. Then it interprets the bytecode. And then, like we talked about before, there can be different conditions that trigger more serious compilation steps. Because think of it this way like it costs more to compile something, but if you're running that code a lot, it pays off in the long run, right? And so that's what the browser is literally always doing. Like, in fact, that's like most of the optimizations we see today. It's sitting there going, is it gonna be worth it for me to compile this? Is it gonna be worth it? Did this change since I last compiled it? Do I need to recompile it? You know? So it's like running this all the time. And so that's what the browser does. It interprets it and then basically sits there trying to figure out what it should compile. And once it compiles it, you might have a mix of like interpreted and compiled code being run at the same time. Um, so knowing that, uh, how can you actually optimize your program? So uh like I always say here, uh, if if you don't know yet, if you're talking performance optimization, and this is a tough quiz question for you, Austin. So just preparing you here. Yeah, I see that look on his face. What do you what do you do first when you have a performance bottleneck?

SPEAKER_00

Well, the first thing, oh man, we we even have like a framework for how we do it, right? That we've had like two episodes on the stream.

SPEAKER_02

Am I allowed to go and put it in a big bold letters for you?

SPEAKER_00

Okay, good. We uh we profile.

SPEAKER_02

Yeah, I just want to say, like, we we have a lot of like that's good, Austin. Yep.

SPEAKER_00

No, like we you and I have like dictionary uh mismatches half the time, and I was like, oh man, I don't know if this word's in my dictionary. And I saw profile in the show notes, and I was like, if I just like blurt that out, I'm just gonna look like an idiot too.

SPEAKER_02

No, you're good. That's it. That's it. Profile.

SPEAKER_00

Like, there's all you could go on the internet or listen to us here, and there's a bunch of little things you could do to make your code run faster, but by far the most important thing is if you have a bottleneck profile, like that's just and when you mean profile, like we're talking about like we're going to analyze like what like what is being run, what are like what's coming back at you in in the console, in the going into like the React profiler itself. What yeah, what profilers exist within just JavaScript?

SPEAKER_02

So the browsers uh like Firefox and and Chrome at least. Um I can't speak to Safari, but I assume it does, um, although it is Apple so they might leave stuff out, but most of them have uh have profilers for JavaScript. Uh and so you can actually see what what it's doing, and you know, just like we do for React. So yeah, you're right. You're exactly right.

SPEAKER_00

Well, where do you okay? So in Chrome, where do you access the profiler for just a JavaScript site?

SPEAKER_02

Um that is a good question. Uh performance tab. So you go to performance tab and you can record a sample uh uh do a recording just like you do for the um React profiling. It's like the same thing, just a little bit different views, but basically the same thing.

SPEAKER_00

Right on.

SPEAKER_02

Yeah. Um so uh beyond just profiling, like is there stuff we can take away from what we've learned today in the code you write? So one thing that you know is something that happens to be talked about a lot in the React community um is you know loading or sending all of your React code to the browser on initial load. Um, why would you maybe not want to do that? Well, now we know it would have to parse and byte code compile it all. And so um if you have facilities, um shoot, I'm blanking on the the React term for splitting up your program at the moment, but we did also talk about the React server components recently. Um, but any of those facilities where you're not sending all of the the browser code at once can make your initial load faster because the browser just has less to parse and and bytecode compile up front.

SPEAKER_00

Does uh where does like I think you can like lazy load in components with Next.js currently uh yeah, yeah.

SPEAKER_02

React that's a React um feature. That that's the one I'm talking about that I'm blanking on, but yeah. Uh anyways, yeah, so you can you can definitely it's just code splitting, I believe. Uh oh, and you have uh suspense, does that also facilitate that?

SPEAKER_00

I believe so.

SPEAKER_02

Yeah, so there's ways to do it. Um it's just something to be aware of. I don't I mean, yeah, I think if you I think there's definitely cases where this long parse and and bytecode compile and and everything can be be an issue. Again, I would try to see if you could profile it first to pinpoint that, but just something to be aware of, I guess. Um here is one though that is actually important and you don't need to profile to know it. And that is um if you're doing visual updates, don't use set timeout or set interval, always use request animation frame. Those are just JavaScript APIs. Uh so in React world you uh they have um shoot, I should have like gotten this ahead of time. There's a like you know how you have the like um uh timeout hook? Uh there is a an we haven't we had it in our uh episode, I can't remember it. There's like request animation timeout or something. I'm sure you could figure it out if you're you're looking for it. Um but yeah, that is like what you would use if you're like actually manipulating the DOM. But the reason why you don't usually see it in React Code is because you don't usually manipulate the DOM directly in React Code. That's very rare. Um, so usually in React Code, set timeout, set interval are are fine. Um but I just wanted to call that out. If you're doing some really wacky React stuff um where you're like actually making visual updates outside of the normal React way, you'll definitely want to make sure to use the right API from React. But if you're just um writing like a non-React library, this is also important um to know that distinction. And uh I mean, I'm sure everyone is like, okay, you're telling me this, but why? Right?

SPEAKER_00

Yeah, why Thomas? Why should I care?

SPEAKER_02

Why why yeah, exactly. So this goes back to the um the threads. So if you request animation frame, it actually allows the browser to run um other code without essentially waiting for all of your code to finish running. Um, and if you don't do that, it can just end up in the okay, so I I need to re-explain that. So there's essentially two event cues. There's the regular event queue, which is where set timeout and set interval go. There's the high priority event queue, basically, which is where request animation frame callbacks would go. And so if you put something in there, it supersedes whatever might be in the other queue. And that's important if you're making visual updates so that it feels it like feels smooth and continuous. You're not getting jankiness by having to wait for a bunch of other things that got in the queue. Does that make sense?

SPEAKER_00

Yeah, so um where like say you run like you run a function handle handle some interaction, right? And you would put the entire handler inside uh as the callback, uh, if there were uh animation elements like at the beginning and end of it, you would you're saying?

SPEAKER_02

Uh I mean, yeah, any like if it would depend on your program, but like uh yeah, if you had an animation, obviously that's one of its primary reasons. The actual parts that update the UI need to be in in the request animation frame.

SPEAKER_00

Okay.

SPEAKER_02

Yeah. Uh and why I was like sort of hesitating is because yeah, you might have to run some other code in between to calculate things or whatever, and you'd want to minimize that because you're basically in high priority mode there, of course. Um but yeah. I believe so. I also put this in here is because I believe this is actually what React uses to schedule a lot of things too. And um, so I just thought that was interesting. Like we had that episode and we talked about like how does React actually render and stuff. Um, this is part of its algorithm is figuring out which things should go in the normal queue and which things should be in the request animation frame queue. And the actual like DOM updates, I believe it schedules in request animation frame. And I'm also bringing this up because think about it this way. Like, if you are, and Austin was kind of touching on this, like if you run gigantic chunks of code in there, it like defeats the purpose. And so that was why um with uh React and Hooks and the like sort of way that React created their own like scheduler that we had talked about previously, um, it can use request animation frame to update the UI and keep the UI appearing smooth while it's doing a bunch of work still. So it's sort of like essentially, you know, we have one thread, but we're able to, you know, preempt work and make the UI seem smooth, even though we're not done doing all of our work. So I thought that was really cool. But I don't know, did that make any sense, Austin?

SPEAKER_00

I IS it does. Uh I was looking further into uh using request animation frame within React while while we were talking and uh couldn't find the reference we we had mentioned earlier.

SPEAKER_02

Oh, I thought it was just on the like same page as like set timeout or something, but anyways, I'm sure people can find it, or we'll add it to the the um show notes or something that we put out with the episode. Um yeah, so um moving on, um the uh something else you may have heard of is web workers. Um so if you have long running like JS code that isn't updating the UI or needing to interact with the UI too much, um, you can run that in a web worker, uh, which is basically just running it in another thread. So that is a way to like not run your code on the main thread, but you can't do a lot of stuff from web workers that you can from the main thread for the reasons we talked about earlier. Um and so uh another thing that um if we're talking about compilation, so a big thing that you can do to make your code just in general run faster is keep your types the same. So uh think about the compiler. It's running an optimization step like on that const x equals one plus two. What if it was const x equals one plus y? And sometimes y was the number two, and sometimes y is the string A, which is valid JavaScript. You could it you could do one plus the string A, right? Well, how is the compiler gonna optimize that if you're changing types on it? And that's a very trivial example. I'm talking more at like the function level, like if you're passing something into a function and you keep the type the same, you're gonna get better performance because the compiler can actually optimize it. Um so that's the same for like classes, functions, especially. Like at basically anywhere you can, don't change types. Um yeah. So that's a an easy thing that I think anyone can do. And I I don't um so you know, going back to my theories on on programming and programmers and and everything, this isn't something where I would be like in a code review, you change types, you're a terrible person. Because I think there are times where it makes sense. Um, but like it's something that, especially if it's in your inner loop, in a loop or you're mapping over something or whatever, code that's gonna get run a lot, um, it's definitely gonna pay off if if you follow that rule. Did you know about that one, Austin?

SPEAKER_00

No, I wasn't uh aware of the of that at all.

SPEAKER_02

Yeah, I mean, the the truth is compilers aren't that smart. Like they seem really smart and cool, but like in the grand scheme of things, they're they're not you know as super intelligent. And so keeping your program like running in a similar way in general is gonna generally help compilers, you know. Once you start doing tricky stuff. They get confused.

SPEAKER_00

So yeah, the more the more you like the establish a paradigm in how you program and use existing patterns within your software, the more efficient your code will actually become through the interpreter and the compiler working together, right?

SPEAKER_02

Yep. Yeah.

SPEAKER_00

That's pretty cool to it it like actually uh like takes on your your interpret how you've written your code and that that's pretty cool.

SPEAKER_02

It's kind of like alive but not yeah yep yeah it is yeah I I agree. It's pretty cool. I I like that way of thinking of it.

SPEAKER_00

Yeah it's like dynamic I guess like depending on how dynamic you are in the way you write it.

SPEAKER_02

Yeah and like um this is different than like maybe a more traditional way of like writing a a C program or something where you're just like compiling it once and and that's it. The the browser compilation interpreter stuff is very trying to be intelligent.

SPEAKER_00

You know like it's it's really trying to do the best thing in all these different cases you know so it really like it is really really intelligent but it's limited by what we can express currently for it to digest based on its rules.

SPEAKER_02

Yeah exactly yeah um another another little tip is at least for V8 um if you declare properties in the constructor for objects um that also helps the compiler because that the compiler is essentially gonna yeah I won't get into the like uh I we don't go back to components and not do functional components is we don't have enough background for me to explain exactly why that's beneficial but like yeah and I want to say I guess tagging on that like I don't I I basically don't do these things on a regular basis. So we're talking about them here because I think it helps make like force our brains to to think through and understand how this stuff works. And I know some people love to do them. I personally only do these optimizations after I've profiled and found that I need them. Now there's some of these like keeping types the same I think is good programming practice generally like it gets confusing if types change. But a lot of these you know and and like the set timeout request animation frame those are just things you need to know if you're gonna be working with that kind of stuff. But like in terms of like trying to like guess what the compiler is going to do and stuff the thing to keep in mind is that changes.

SPEAKER_00

So all that stuff I told you about it it's probably going to change to some extent five years from now and we'd have to make a new episode every year to tell you the latest things which is cool but like it's not like a permanent thing you can just remember you know could you loop back to the types uh again like when you're talking about types where at what level are you talking about their definition? Um is it down to like the the types of variables you're declaring or like larger structures of custom types or or could you go over that again?

SPEAKER_02

Yeah it's pretty simple like say you have a function that has an argument um A B C or something I'm just saying don't change the type of that like every time you call that function A B C should be the same type whether it's a string or a number or does that make sense? Yeah just okay at the at the variable declaration level yeah yeah you don't want to be doing different types so like even if you yeah have like const x equals an uh object literal in one sent one time and then it's a number the next time or the the one thing that I don't know and I don't know if we need to look into more is how that plays with like null and undefined and and things like that. I assume you can interchange those but I don't know if they're technically considered a different type you know for the compiler optimization algorithm. But like yeah just don't like pass in a string one time for the same variable and then a number the next time or something that that like will mess up any compiler and interpreter in basically any language. So just like not great idea.

SPEAKER_00

Right. Yeah and if you do if you do if you like what if you're not aware of a string going in versus a number maybe something comes back uh from the server it's an op it's good to just like make sure that the first thing you do inside of the function is convert it to what you expect it to be if it's not is that over optimizing or just like no don't like just make sure you're passing in the right thing.

SPEAKER_02

I mean I would say fix your server um but like like there's it's not a hard and fast rule. I think if you so and again like if you if it happens every once in a while it's not gonna be a huge deal but if like every other time your React component renders it's changing the type of something you're never gonna get optimizations in that area.

SPEAKER_00

Right. Yeah but I love I love that idea it's like being a a jerk yeah just like create a a helper function that's like hey you should be a a string or you should be a number.

SPEAKER_02

Have you ever heard of uh it's actually this new fancy thing called GraphQL oh yeah yeah it actually has typing I guess we better uh make the switch then uh yeah yeah uh all right well uh I think that about um wraps up what I had in mind for today you know we took a look at the sort of high level of parsing and ASTs interpreters compilers threads event cues um and then took a little bit more um look at you know how how do browsers actually put those together to run your code these days um which I and how they used to in the past yeah and how they used to in the past exactly yeah I think that's pretty cool um and some little tips on on optimizing and how you can take advantage of this um yeah I had a lot of fun I love this topic um I yeah if you if you don't know uh uh much about me I like to write interpreters and compilers so it's it's uh it's definitely one of my favorite subjects um and yeah if if anyone else has feedback about this and you know definitely let me know and I know we didn't get into like you can get into super details on this like there's way other optimizations you can do um I'm I was aiming for a little bit of a a high level like just help you understand how it works type of thing but if you guys are interested in I don't know even more details you know certainly let us know um I can I can have Austin whip that one up for us.

SPEAKER_00

Yeah let me add it man well I just I thought it was a cool episode because it really showed how like your your bad code or your optimized codes like actually scales and like how it does like with how the interpreter can take what's bad and just like run with that in the wrong direction right yeah um or if it if you it's it does a great job if you've written properly and then how that how it all builds upon each other all these different layers it's pretty pretty amazing what what we're able able to work with every day.

SPEAKER_02

Yeah it's uh so I also kind of come from like a C level background you know where it's not uncommon to like disassemble the output from the compiler and like analyze it and be like oh why did it optimize it this way and oh I need to do this to like have loop unrolling and like that you you could really go down this road but I think the cool part about the browser situation is it's like so I don't know dynamic like you were saying like it's not even that's not even really a thing like you just write your code and and that's it and you could profile it but like I don't know it just has so many different ways of running it. I just find it fascinating.

SPEAKER_00

Yeah it's pretty cool stuff. I really love the the topic of uh today's episode too how how JavaScript actually executes yeah I don't I guess I hope we cover that but it sounds good yeah I think I think so uh well our top episode of all time so far is how your app actually executes it's like the perfect the perfect episode you picked man for where we're going to even realize that I probably like my brain just somehow it's like this is an optimum optimized title type.

SPEAKER_02

Yeah I do have a a title optimizer actually running in my brain now so you're that's pretty that's that's rare stuff man um thanks for joining us once again in our title optimized episode uh we hope you have a great rest of your day bye