Understanding the Runtime and the Language of JavaScript: A case for a better Web Developer

Understanding the Runtime and the Language of JavaScript: A case for a better Web Developer

·

8 min read

It is important to understand the whole concept behind how JavaScript works and how the code you write get interpreted by the underlying OS. Having that knowledge under the hood will make you a better web developer. in this article, I will attempt to explain how the javascript runtime engine works, its relationship with the browser and how the execution of your javascript code get translated to the computer OS that actually implements the logic written in your code.

Without much ado, lets get started. shall we?

Each browser has a Javascript Runtime Environment. Most browser has its own version of a JS engine. Google chrome browser uses the V8 engine; Internet explorer uses chakra ; mozilla firefox uses Spidermonkey and so many others.

Table of content

  1. The Javascript Environments
  2. The Runtime Engine (syntax parser)
  3. The Javascript Language

The Javascript Environments

The javascript engine is like a container sitting in the browser. The engine is a program responsible for translating source code into machine code (language that the computer understands) and executing the translated result on a computer’s central processing unit (CPU). There are other component of the browser that are not part of the engine but allows interaction with the javascript engine like the; webAPI (networking, data storage and graphics). Once the engine receives your javascript code or scripts on the web page the Engine starts parsing it with a syntax parser. First, it will partially parse the code checking for syntax errors, if it finds none, it starts reading the code from top to bottom. Its ultimate goal is to turn the javascript code into machine code that the computer can understand. But before we understand what exactly it does with the code we must understand the environment in which it is parsed.

1.1 Browser Environment The environments that javascript runs is referred to as host environment. A platform may be a browser, or a web-server or another host, even a “smart” coffee machine, if it can run JavaScript. Each of them provides platform-specific functionality. A host environment provides own objects and functions additional to the language core. Web browsers give a means to control web pages. Node.js provides server-side features, and so on.

browser_environment.jpg

The image above depicts a typical browser environment that host the JavaScript engine, it provides other input/output such as networking, storage, or graphics facilities. it allows access to objects like:

//popup
window.alert();

//current HTML URL
location.href;

//Forward or backward specified number of pages
//Positive for forward, negative for backward
history.go();

//Returns the string of the user agent header
navigotor.userAgent;

// Get an id of an element from the HTML document
document.getElementById("intro");

// window time out and interval that accepts a function(fn) and 
// runs at a specified time (ms)

window.setTimeout(fn, ms)

window.setInterval(fn, ms)

...

The Runtime Engine (syntax parser)

It all starts with the JavaScript code you write. The JavaScript engine parses the source code and turns it into an Abstract Syntax Tree (AST). Based on that AST, the interpreter can start to do its thing and produce bytecode. Great! At that point the engine is actually running the JavaScript code.

V8 Inside.png image credit from: javascript-1.gitbook.io/javascript/v8-engine

When the javascript engine starts running your code, it progresses through reading in the code from the source, then it will validate the code against any error, if none is found, it then starts reading the code from top to bottom. after reading the code, it will produce an Abstract syntax tree (AST), i.e how each part is connected to one another. After the AST process is completed, another part of the engine called the interpreter, will then convert the AST to a bytecode. To make it run faster, the bytecode can be sent to the optimizing compiler along with profiling data. The optimizing compiler makes certain assumptions based on the profiling data it has, and then produces highly-optimized machine code.

However, at the cpu level, were the execution of the code happens, a track of the code block and its execution context (an environment in which a function executes) is kept in the call stack(The call stack is a collection of execution contexts). Every data in the call stack will be pointed to the memory heap. It follows Last In First Out (LIFO) data structure. When the code is executed, javaScript run time is created. When the function are pushed into the call stack, the functions belonged to Web API will be send to the Web API by call stack for the process. When the web API receives the function, it will process the functions, and then it is send to the call back queue. Then the processed function in the call back queue will be send to the event loop to send to the call stack. After receiving the processed function, event loop pushes the function to the call stack, when it is empty. ( waits until the call stack is empty ). Then the function will be executed in the call stack.

js_runtime.png

image credit from: javascript-1.gitbook.io/javascript/javascri..

2.1 The Call Stack

The Call Stack is a collection of the execution context where the actual code is being executed or invoked. Each code execution is referenced to a scope. There are two type of scope when the javascript runtime engine starts to execute; global scope and the function scope. Whenever we run the javascript code, it creates a global execution context that gives global object.

// The global object 
window //and
this
//and
this === window
...

After the global execution context is created, functional execution context will be created. Each functions to be invoked, are called with the last in, first out structure. that explains why javascript engine is referred to as being single threaded in nature.

The Javascript Language

For newbies, JavaScript is the world's most popular programming language. It is a scripting and interpreted programming language. it is also a high-level, object oriented and functional programming language. it is also a multi paradigm, single threaded programming language. There are many aspect of the language that demands in dept understanding before you can really grasp the concept; the language, the environment and the tools used in the javascript programming. There is a enough resources about javascript on the internet, but one concept that helped me when i started off with javascript, was viewing everything as an object. The knowledge of where those objects are, in the scheme of things, that is the environment where the object is defined, how it is connected with other objects, their properties and methods, the composition of the object in formulating a logic, how it will interact with external environment like getting data from data source or being used as property of another object, all combined to gave me a clear metal picture of the language syntax, its environment and the tools required per context.

Apart from having knowledge of the data type, one important topic to pay close attention to, are the; syntax parsers, the execution context and the lexical environment. learning these three concept will really help in your deep understanding of javascript language under the hood.

A simple example of javascript code entail everything as mentioned above:

// The global scope(environment-execution context)

// variable is defined, and its has a value as function. 
// the function is defined in the global scope
const SayHello = hello => {
//The function scope(environment-execution context)

//the variable `hello` is defined in the SayHello environment 
// and has its `this` bounded // to the boject
this.hello = hello;
...
}

A close look at the name/value pairs and object is as important as single threaded, synchronous execution. Also, types and operators, objects and functions, object oriented and prototypal inheritance, building objects and so many more. The language encompasses a whole lot, but deep understanding of the sections mentioned above will give you a leverage and sets you on the right path. The code you write is basically a bunch of object created, just like composing a letter with grammars, you compose the objects created with variables and functions. When the javascript engine encounters your code, it would run a test on it, and determine if any error is present and that the code is true. if all goes well, it would produce a syntax tree, that had arranged and organised the code, the syntax tree would then be fed to the interpreter which in turn would produce the bytecode. The bytecode is later optimized further and then executed by the CPU when loaded into memory.

In conclusion, understanding the Runtime and the Language of JavaScript, will help to solidify your knowledge of the language and in turn makes you a better web developer. I will be updating this space on concepts that i finds fascinating and it will serve as means of expressing my level of knowledge in this weird langauge:javascript.

If you find this article useful and may want to encourage me to write more, do subscribe and also follow me on twitter

Happy coding!