Skip to main content

Command Palette

Search for a command to run...

The Structure of JavaScript

Updated
•7 min read•View as Markdown

If we come from a web development background we all know what JavaScript is. Even if we have just started to explore it we would know what JavaScript is. But JavaScript is a language that has some nuance to its existence . As such understanding the nuance behind how it behaves will help us to code with a much clearer understanding of what is happening and most importantly how to debug when something goes wrong.

What is JavaScript

Here we will try to look at the origins or JavaScript. Earlier when HTML and CSS existed along with a server - the architecture was - >

User Requests a static page -> Fetch that Static Page from Server -> Display it.

And as you can guess - it was boring. Static pages only. Not only that for basic things like form validations or small logic checks they had to be performed on the server. Imagine the bandwidth of the network that needs to be kept uselessly busy. At that time no one was worried about animations or event based features. Being able to run basic logic in the browser itself would make them happy. At that time a browser named NetScape used to exist. The company NetScape Communications asked an employee - Brendan Eich to create a scripting language for Browsers that would allow web pages to behave like applications.

.

.

.

In 10 days.

YES IN 10 DAYS!!

And he compiled. Hence a scripting language for web was created. They called it Mocha then LiveScript and then finally JavaScript. Often you must have heard people saying there is no connection between Java and JavaScript but there is. They used this name to attract people who were already using Java, because it sounded similar. This was to confuse them as a part of marketing. So now we can say that JavaScript was a simple to use scripting language designed to bring logic to the web pages on the browser.

Later when everyone started using JavaScript they made their own features which caused conflicts causing a need for stabilization that was bought about by an organization called Ecma International. The specification is officially called ECMAscript .

The Workings of JavaScript

Unlike C or C++ which have gcc or g++ compilers to convert them into executable machine code - JavaScript is executed in specialized engines that run inside browsers. These engines parse the JS code, convert it internally and are executed. The answer to the question as to whether JavaScript is a compiled or interpreted language is not very black and white and can be said to be as a mixture of both.

Now to be able to run JavaScript 2 things are needed.

  1. A JavaScript Engine
    We have many JavaScript Engines like:

    V8 - Chrome , SpiderMonkey - Firefox , JavaScriptCore - Safari etc.

  2. A runtime Environment
    Here we have - nodejs , browser itself , deno , bun etc. It is important to note that different runtime environments offer some same and some distinct features.

So how does the execution take place?

The Execution of JavaScript

The execution of JavaScript starts with the creation of what can be virtually thought of as a box - called the Global Execution context. Before execution JavaScript performs a scan of the entire code to allocate memory. This is equivalent to us skimming though the pages of a book to get a rough idea as to what it will be about before going into it seriously. Now when we are at this stage. JavaScript starts the execution of each line one by one. If it encounters a function - it creates a new execution environment and performs the same task - scan, memory allocation execute and return result.

This new task is pushed onto what is called the call stack. Its job is to keep track of the tasks needed to be executed. The first element to go into the call stack is Global Execution Environment and the execution isn't complete until the call stack is empty.

This feels pretty complicated to understand and hence I suggest using online tool visualizers to understand the flow like: https://pythontutor.com/javascript.html#. But I will try to give an understanding here using practical code example.

var a = 10;

function add (a,b)
{
  return a+b;
}

console.log(add(a,10));

As the execution starts first the code is Scanned and something like this can be imagined.

GLOBAL EXECUTION CONTEXT

1. A variable named a exists (it sees the value as undefined for now)
2. A function named add exists (stored with entire function definition)

![](https://cdn.hashnode.com/uploads/covers/696be33fcfe0ce5a321590b9/b31c1200-c32e-4760-8af7-6aefa90f047c.png align="middle")

Now execution starts line by line:

On execution of first line :- we get GEC updated:

GLOBAL EXECUTION CONTEXT

1. A variable named a exists with value 10;
2. A function named add exists (stored with entire function definition)

![](https://cdn.hashnode.com/uploads/covers/696be33fcfe0ce5a321590b9/b7dc7184-5df6-4d4f-833c-f6878aa72f4a.png align="middle")

On execution of the second line the engine will create a new execution context and perform the scan step:

ADD FUNCTION EXECUTION CONTEXT
1. A variable named a exists with value 10 (passed to it)
2. A variable named b exists with value 10 (passed to it)

![](https://cdn.hashnode.com/uploads/covers/696be33fcfe0ce5a321590b9/1c300204-54d7-4045-8260-217090f0a9df.png align="middle")

Then the return value is calculated on the execution of the line in the function.

ADD FUNCTION EXECUTION CONTEXT
1. A variable named a exists with value 10 (passed to it)
2. A variable named b exists with value 10 (passed to it)
3. Return value is 20

![](https://cdn.hashnode.com/uploads/covers/696be33fcfe0ce5a321590b9/4800eb62-b4b7-4702-bfbc-1e5a4a7e37f2.png align="middle")

Now this execution environment will be popped from the call stack (being called as a frame here and the value will be returned).

Finally the last line console.log will be executed and the Global Execution frame will also be popped from the call stack ending the execution.

Hoisting

Hoisting is a behavior of JavaScript whereby which after the scan phase of the code variable and function declarations are moved at the top of the scope to be accessible. Any variable declared as var will be stored as undefined. If in code they are accessed before they are allotted then they show undefined and if the line where the value is declared is executed then it shows that value. The var declarations are always stored as undefined even if the first line of the code assigns it value along with definition . The value won't be available until the line that defines the value is executed. However functions (that are not assigned to a variable) are present and can be accessed directly.

For example:

console.log(element);
var element = 10;
console.log(element);

//output
//undefined
//10

This is the output. First element was accessed when it was undefined then the line that defined it executed and then finally we get the correct value.

However for functions we can do:

add(2.3);

function add(a,b){
 return a+b;
}

This is valid syntax because hoisting saves the function definition to the top of scope making them accessible at any point in the code.

A common misinformation is that let and const are not hoisted. They are actually hoisted. But they are not available for use even as undefined. They exist in a virtual zone called the Temporal Dead Zone. It means that they are recognized to exist but are not usable until their value has been defined. Trying to reference a let or const variable before it is defined leads to a ReferenceError that looks like this:

![](https://cdn.hashnode.com/uploads/covers/696be33fcfe0ce5a321590b9/d3fa4bf4-9f1b-436f-9ee1-5f49a070db40.png align="middle")

Also in JavaScript classes too are hoisted but they cannot be accessed before being defined in their source code.

Being able to understand JavaScript at such a level will help you in coding interviews but most importantly they will stay with you as fundamentals. Those who know the fundamentals are capable of creating things in a much more robust manners than those who don't actually understand the underlying mechanics. The level of freedom and calmness one feels when they not only use a language but to understand its very roots will help you bond with the language making you not a programmer but a developer - not because you can code in JavaScript but because you can think in JavaScript.