DEV Community

Cover image for How JavaScript Works🔥 🤖 [Visually Explained]
Narottam04
Narottam04

Posted on • Updated on

How JavaScript Works🔥 🤖 [Visually Explained]

JavaScript is one of the most loved and hated languages in the world. It is loved because it is potent. You can make a full-stack application by just learning JavaScript and nothing else. It is also hated because it behaves in unexpected and upsetting ways, which, if you're not invested in understanding the language, might make you hate it 💔.

This blog will explain how JavaScript executes code in the browser, and we will learn it through animated gifs 😆. After reading this blog, you will be one step closer to become a Rockstar Developer 🎸😎

https://media.giphy.com/media/EA4ZexjGOnfP2/giphy.gif

Execution Context

"Everything in JavaScript happens inside an Execution Context."

I want everyone to remember this statement as it is essential. You can assume this Execution context to be a big container, invoked when the browser wants to run some JavaScript code.

In this container, there are two components 1. Memory component 2. Code component

Memory component is also known as variable environment. In this memory component, variables and functions are stored as key-value pairs.

Code component is a place in the container where code is executed one line at a time. This code component also has a fancy name, namely 'Thread of Execution'. I think it sounds cool!

Execution context

JavaScript is a synchronous, single-threaded language. It is because it can only execute one command at a time and in a specific order.

Execution of the code

Let's take a simple example,

var a = 2;
var b = 4;

var sum = a + b;

console.log(sum);
Enter fullscreen mode Exit fullscreen mode

In this simple example, we initialize two variables, a and b and store 2 and 4, respectively.

Then we add the value of a and b and store it in the sum variable.

Let's see how JavaScript will execute the code in the browser 🤖

Execution context 1.1

The browser creates a global execution context with two components, namely memory and code components.

The Browser will execute the JavaScript code in two-phase

1> Memory Creation Phase

2> Code Execution Phase

In the memory creation phase, JavaScript will scan through all the code and allocate memory to all the variables and functions in the code. For variables, JavaScript will store undefined in the memory creation phase, and for functions, it will keep the entire function code, which we will be looking at the following example.

Execution context 1.2

Now, in the 2nd phase, i.e. code execution, it starts going through the whole code line by line.

As it encounters var a = 2, it assigns 2 to 'a' in memory. Until now, the value of 'a' was undefined.

Similarly, it does the same thing for the b variable. It assigns 4 to 'b'. Then it calculates and stores the value of the sum in memory which is 6. Now, in the last step, it prints the sum value in the console and then destroys the global execution context as our code is finished.

How Functions Are Called In Execution Context?

Functions in JavaScript, when you compare with other programming languages, work differently.

Let's take an simple example,

var n = 2;

function square(num) {
 var ans = num * num;
 return ans;
}

var square2 = square(n);
var square4 = square(4);
Enter fullscreen mode Exit fullscreen mode

The above example has an function which takes an argument of type number and returns the square of the number.

JavaScript will create a global execution context and allocate memory to all the variables and functions in the first phase when we run the code, as shown below.

For functions, It will store the entire function in the memory.

Execution context 1.3

Here comes the exciting part, When JavaScript runs functions, it will create an execution context inside the global execution context.

As it encounters var a = 2, it assigns 2 to 'n' in memory. Line number 2 is a function, and as the function has been allocated memory in the memory execution phase, it will directly jump to line number 6.

square2 variable will invoke the square function, and javascript will create a new execution context.

Execution context 1.4

This new execution context for the square function will assign memory to all the variables present in the function in the memory creation phase.

Execution context 1.5

After assigning memory to all the variables inside the function, it will execute the code line by line. It will get the value of num, which is equal to 2 for the first variable and then it will calculate ans. After ans has been calculated, it will return the value which will be assigned to square2.

Once the function returns the value, it will destroy its execution context as it has completed the work.

Execution context 1.6

Now it will follow a similar procedure for line number 7 or square4 variable, as shown below.

Execution context 1.7

Once all the code is executed, the global execution context will also be destroyed, and this is how JavaScript will execute the code behind the scene.

Call Stack

When a function is invoked in JavaScript, JavaScript creates an execution context. Execution context will get complicated as we nest functions inside a function.

Call Stack

JavaScript manages code execution context creation and deletion with the the help of Call Stack.

A stack (sometimes called a “push-down stack”) is an ordered collection of items where the addition of new items and the removal of existing items always takes place at the same end eg. stack of books.

Call Stack is a mechanism to keep track of its place in a script that calls multiple functions.

Let's take an example

function a() {
    function insideA() {
        return true;
    }
    insideA();
}
a();
Enter fullscreen mode Exit fullscreen mode

We are creating a function 'a', which calls another function 'insideA' that returns true. I know the code is dumb and doesn't do anything, but it will help us understand how JavaScript handles callback functions.

Call Stack

JavaScript will create a global execution context. Global execution context will assign memory to function 'a' and invoke' function a' in the code execution phase.

An execution context is created for function a, which is placed above the global execution context in the call stack.

Function a will assign memory and invoke function insideA. An execution context is created for function insideA and placed above the call stack of 'function a'.

Now, this insideA function will return true and will be removed from the call stack.

As there is no code inside 'function a' execution context will be removed from the call stack.

Finally, the global execution context is also removed from the call stack.

Reference

https://media.giphy.com/media/l4pTjOu0NsrLApt0Q/giphy.gif?cid=ecf05e47dtlkk3fe19ovkz96zbsihgjhtu6injewu9oy5v8e&rid=giphy.gif&ct=g

I hope this post was informative. 💪🏾 Feel free to reach out to me if you have any questions.

For more such insights, checkout my blog website blog.webdrip.in

Discussion (88)

Collapse
shreedhar37 profile image
Shreedhar Chavan • Edited on

Atleast give credits to content owner!!

Collapse
dylzeee profile image
dylzeee • Edited on

ummmm no, namaste js is not the first guy to visually explain javascript like this. Nor is the poster of this.

Collapse
balapriya profile image
Bala Priya C • Edited on

This post is indeed heavily inspired by Akshay Saini's Namaste JS series - examples, flow of concepts etc. It would have been great if the author had included a line in the post instead of sharing link to the playlist in the comments section.

Thread Thread
dylzeee profile image
dylzeee • Edited on

Still, can't call him the 'content owner' as the first commenter did though. This poster has taken common knowledge about javascript and taken the time to visually express it in a unique way. He also linked to his source of knowledge in the comments as you say, which he didn't need to do.

Does that mean every time I create a website and put my name/logo in the footer, I also need to mention the 300+ resources that have taught me something or inspired me....no.

Namaste js, most likely learnt it from somewhere too, maybe one of the many books he has on his desk in the bg, does he give them credit? He often is reading something in his video, probably words of others, does he give credit?

Thread Thread
balapriya profile image
Bala Priya C • Edited on

Yes, I agree that Namaste JS is not the content owner - and the first commenter is not right to phrase it that way. And I totally agree on the great efforts in creating engaging visuals.

However, when almost the whole content of your post is this particular video in the playlist - it doesn't really hurt to mention it in the Reference section in the post.

There's clearly a difference between writing tech tutorials inspired by a lecture series, and developing a website.

When writing tech tutorials, it's often a good practice to mention the references.

It's totally fine if you don't quite feel the need to acknowledge. I only wanted to get across my message.

Thread Thread
narottam04 profile image
Narottam04 Author

Noted and rectified my mistake😄! I thought adding references on the comments section will be sufficient.

Thread Thread
balapriya profile image
Bala Priya C

Thank you for accepting the suggestion positively. ☺️ You're doing an amazing work. Have you considered submitting your posts to javascriptkicks.com?

Thread Thread
narottam04 profile image
Narottam04 Author

I didn't knew about this website, I will consider looking into it, Thanks😄

Thread Thread
balapriya profile image
Bala Priya C

You can submit posts here for a wider reach to the JS devs. And there's a Medium publication JS in Plain English - that'd be a great place to share as well. And then, include the canonical url in the dev.to posts so that we can read it here too.

Collapse
hamiecod profile image
Hargunbeer Singh

Is it somebody else's content?

Collapse
shreedhar37 profile image
Shreedhar Chavan
Collapse
narottam04 profile image
Narottam04 Author

Awesome YouTube playlist to learn more about JavaScript:

I hope y'all will like this!

Collapse
domagojvidovic profile image
Domagoj Vidovic

This is a unicorn for sure. Amazing!

Collapse
narottam04 profile image
Narottam04 Author

Thank you!

Collapse
bobbyiliev profile image
Bobby Iliev

This is amazing! Well done!

What tool did you use to create those amazing animations?

Collapse
narottam04 profile image
Narottam04 Author

PowerPoint 2019

Collapse
efraimla profile image
Efraim

Old school, like it. Great work

Thread Thread
narottam04 profile image
Narottam04 Author

😂yes, couldn't find better tool for it. If there is a better tool than PowerPoint lemme know

Collapse
k3nnet profile image
k3nnet

this is golden . thanks so much for this .

Collapse
narottam04 profile image
Narottam04 Author

Glad you liked it!

Collapse
narottam04 profile image
Narottam04 Author

Thank you!

Collapse
lannex profile image
Shin, SJ

This is a good post.

Can I translate this into Korean?

Collapse
narottam04 profile image
Narottam04 Author

Sure! you can do it. Just add my twitter profile or link back to this blog.

Collapse
lannex profile image
Shin, SJ

You bet!

Collapse
mpagels profile image
Martin Pagels

You can use this tool to visualize the execution of Javascript (and other programming language:
pythontutor.com/live.html#mode=edit

Collapse
narottam04 profile image
Narottam04 Author

This is awesome! Thanks for sharing it.

Collapse
dimsane profile image
Dwaipayan Sen

Sir Saini will be so pleased! Thanks for such a wonderful presentation @narottam04 .

Collapse
ameerrah9 profile image
Ghameerah McCullers

This was really helpful!

Collapse
narottam04 profile image
Narottam04 Author

Thank You!

Collapse
mhgsam profile image
MHG SAM

Awesome contents.🕸

Collapse
bobbycrooz profile image
bobbycrooz

This is really great, good post

Collapse
narottam04 profile image
Narottam04 Author

Glad you liked it!

Collapse
shrushtiasutkar profile image
ShrushtiAsutkar

Well explained

Collapse
rajissctrl profile image
Sarafadeen Sanjo Raji

Very helpful!

Collapse
korwalskiy profile image
AbdRozaq

I totally agree with you that understanding the execution context if critical to getting a hang of javascript

I also like how you explained the hoisting concept with the memory context analogy

Collapse
narottam04 profile image
Narottam04 Author

Glad you liked it! ❤️

Collapse
malvinjay profile image
George Arthur

Nicely done. Thanks a lot.

Collapse
narottam04 profile image
Narottam04 Author

You're welcome!

Collapse
scapester profile image
Scapester

As a new JS developer, this was extremely helpful.

Collapse
narottam04 profile image
Narottam04 Author

Thank you! glad you found it helpful.

Collapse
smaranh profile image
Smaran Harihar

Brilliantly written. HATS OFF!!

Collapse
narottam04 profile image
Narottam04 Author

Thank you!

Collapse
iamsujit profile image
Sujit M

Nice one man.

Collapse
narottam04 profile image
Narottam04 Author

Thank you!❤️

Collapse
aman0210 profile image
aman0210

GGs naruto

Collapse
narottam04 profile image
Narottam04 Author

💪

Collapse
dikecode profile image
Dike-Code

Thanks a lot for this compelling content... Was really valuable and it's worth bookmarking.

Collapse
narottam04 profile image
Narottam04 Author

Thank you! Glad you liked it!❤️

Collapse
hamiecod profile image
Hargunbeer Singh

Great Post! Keep it Up

Collapse
narottam04 profile image
Narottam04 Author

Thank you!

Collapse
lakshyachopra profile image
Lakshya Chopra

This was amazing, thanks a lot!

Collapse
narottam04 profile image
Narottam04 Author

Welcome!

Collapse
seankimdev profile image
Sean Kim

Amazing! It’s so easy to follow and understand. It solidified the concept for me. Thank you so much!

Collapse
narottam04 profile image
Narottam04 Author

Glad you liked it! ❤️

Collapse
anitaparmar26 profile image
anitaparmar26

Nice

Collapse
narottam04 profile image
Narottam04 Author

Thank you!

Collapse
shubhamshejaval profile image
shubham shejaval

Loved it

Collapse
narottam04 profile image
Narottam04 Author

🙌

Collapse
kurapikachu profile image
kurapikachu

This post is super straightforward for a newbie as me. Thanks a lot!

Collapse
narottam04 profile image
Narottam04 Author

Glad you loved it! ❤️🥳

Collapse
christimamarys profile image
Christima Mary S

Very well explained! Thank you.

Collapse
narottam04 profile image
Narottam04 Author

Welcome!

Collapse
yjsmr profile image
Yonas

Thank you for explaining it like this! Awesome :)

Collapse
narottam04 profile image
Narottam04 Author

Glad you liked it!

Collapse
mastermind profile image
MasterMind • Edited on

Wish I could like this multiple times

Collapse
narottam04 profile image
Narottam04 Author

That means a lot! 🥺 Thank you!

Collapse
dwvicy profile image
Vaishnavi Dwivedi

Wow, this is such a well explained article! Loved it ❤️🙌

Collapse
narottam04 profile image
Narottam04 Author

Glad you liked it!