The JavaScript runtime environment

Have you just started learning JavaScript?

Or maybe you already have some language experience but want to understand JavaScript runtime in more details?

Whatever reason brought you here, there are a few elements of JavaScript runtime that you should get to know.

In this article, I’m going to show you how the JavaScript runtime environment works under the hood. You’ll learn about its elements, their responsibilities, and the way they interact with each other.

Are you ready?

If so, let’s start with the first element of the puzzle.


What is JavaScript engine?

As you may heard before, JavaScript is an interpreted programming language. It means that source code isn’t compiled into binary code prior to execution.

How your computer can understand what to do with a plain text script?

That’s the job for a JavaScript engine. A JavaScript engine is a program responsible for translating source code into machine code and executing the translation result on a computer’s central processing unit (CPU).

The engine is a container in which you run your program.

JavaScript engine resposibility

In Java

Before you run a Java program you have to compile it. This gives you an instant feedback about errors in your code syntax. In JavaScript, you will learn about an issue when the engine tries to execute a problematic line of code.

In order to start coding in JavaScript, you don’t have to install any additional software. Each modern web browser comes with a JavaScript engine. You can simply run scripts you write inside your favorite browser.

All JavaScript engines implement specification of the language provide by ECMAScript. Standardization facilitates the development of independent engines and ensures your scripts give the same results no matter where you run them…

… or at least they should give the same results. Nowadays, the ECMAScript specification changes more dynamically than in the past. Not every engine keeps up the paces.

Java Analogy

Java as a platform also has its specification. Oracle provides the official implementation but it’s not the only one. OpenJDK is another example.
Yet, Oracle’s implementation is considered as the standard. In the JavaScript world, there’s no clear winner.

You don’t have to know in details every existing JavaScript engine but I encourage you to remember engines’ names and web browsers in which you’ll find them. It’ll allow you to check if the latest features of the language are implemented in browsers you want to support.

What are the most important JavaScript engines?

    • Chrome V8 – As you probably guessed the engine shipped in Google Chrome. It’s an open source project written in C++. V8 is also used in Opera, NodeJS, and Couchbase.
    • SpiderMonkey – The open source engine implemented in C++. It’s maintained by Mozilla Foundation. You can find it in Firefox.
    • Nitro – The engine developed by Apple. It’s used in Safari.
    • Chakra – Developed by Microsoft as the JavaScript engine for Edge browser.

But JavaScript engine is just a building block of a bigger concept.

Let’s dig a little deeper.

What is JavaScript runtime environment?

In the web development, you don’t usually use the engine directly. The JavaScript engine works inside an environment, which provides additional features to your scripts that you can use at runtime.

What kind of features you may ask.

These can be utility libraries or APIs which allow communicating with the world surrounding the engine. An example here might be access to information about the web browser in which your script is executed. Or a notification about a mouse click.

Java Analogy

In Java world, we have the Java Runtime Environment (JRE) which gives us access to supporting libraries and acts as a bridge between your program and the operating system.

Is JavaScript single-threaded?

Have you heard that JavaScript language is executed in a single thread?

No more multithreading pitfalls?

Well, it’s not entirely true.

Before you open a bottle of champagne to celebrate simplified development you should first understand what this single thread means to JavaScript.

It’s absolutely correct that your JavaScript code is executed in a single thread. But, it doesn’t mean that the whole JavaScript runtime environment works in a single thread. The thread pool exists in JavaScript runtime. Fortunately, you don’t have to worry about thread management because the environment does it for you.

But how?

How does the JavaScript environment know when to execute your code? If there’s only one thread responsible for the execution of your code, there has to be some mechanism which manages the order of execution.

This mechanism is called the Event loop.

What is JavaScript Event loop?

Before I answer the question, you should know about one important detail. All scripts written in JavaScript can be divided into two major groups.

The first group is composed by immediately invoked scripts. Once they’re loaded, the environment passes them for execution to the JavaScript engine. In the web development, these are usually initial scripts invoked right after a web page is loaded by the browser.

The second group contains so-called event callbacks. An event callback is a piece of code executed when a particular event occurs. In a web page context, an example of an event is a mouse click or a return of a network request.

The Event loop, which is a part of the JavaScript runtime environment, is a mechanism responsible for handling callbacks.

When you create a callback, you always associate it with a particular event. If that event occurs, the environment puts your callback into a so-called Event handlers queue. The Event loop constantly monitors the queue and executes its elements in the order they arrive.

Event loop step-by-step processing

Now something very important!

Callbacks are a l w a y s executed completely. The Event loop runs one callback at a time. No context switching. All callbacks in the queue have to wait until the current one is finished.

If a script runs too long, it blocks others. That’s why callbacks should be relatively short and simple.

Browser JavaScript runtime environment

Although these days JavaScript runs in many different environments, its origins lead to web browsers. One of the main reasons for inventing JavaScript was to put some dynamics in web pages created with HTML and CSS.

First of all, a web browser allows for manipulation of static web pages through the API for the Document Object Model (DOM).

The DOM represents (Models) the tree of UI elements (Objects) in a particular web page (Document). Your web browser creates a DOM object for each page you visit right after it’s loaded.

Thanks to the DOM API exposed by web browsers you can freely change the DOM with JavaScript and add dynamics to static pages.

Document Object Model

But there’s more.

A web browser is an interactive interface for web pages. User click on elements, scroll down pages, or type using the keyboard. All these actions fire user events which the browser exposes as a part of the JavaScript runtime environment.

Beyond that, the user isn’t the only source of events. Your scripts can create events as well.

A very special type of events you create is a timer event. You can delay execution of some code by a specified amount of time. The browser handles these events with the already mentioned event loop.

But that’s not all, you can use browser’s API to communicate via the network with the server side of your application. The result of network communication is also an event.

Finally, a web browser gives you basic information about a host operating system in which it runs and allows to store data in the local storage.

JavaScript web browser environment

JavaScript outside of browser

Although the main environment for JavaScript is a web browser, it wouldn’t be fair if I didn’t mention other JavaScript runtimes.

Why am I doing this?

Because JavaScript is everywhere now.

Think I’m exaggerating?

For a very long time, JavaScript was associated only with the front-end client-side development. Today, the language has much more uses. These include:

  • server-side development – Thanks to NodeJS which is the most powerful JavaScript runtime environment. NodeJS gives you access to the file system, network, and other things which aren’t allowed in web browsers.
  • network – JSON format, which is currently the most popular human-readable format for data transportation, originates from JavaScript.
  • creating mobile applications – Because JavaScript isn’t tight into any particular mobile vendor, it’s a perfect choice for a medium language for different mobile platforms. Frameworks like PhoneGap or Appcelerator Titanium try to provide a unified development environment for different devices and OSs.
  • databases – You can easily find countless ready for use databases implemented with JavaScript. But there are other uses. For instance, the query language for MongoDB is based on JavaScript syntax.

You can actually build a whole web application (from the UI to the data layer) with a technology stack based only on JavaScript. Actually, the stack already has its name and it’s called MEAN stack.

In Java

As you are a Java developer you might not be interested in NodeJS since you probably use Java for the back-end. However, these examples greatly illustrate capabilities of JavaScript runtime environments. JavaScript is no longer just a toy language for fancy UI animations. It can do much more!

JavaScript engine vs runtime environment

At this moment, you probably should be able to say in your words what is the difference between JavaScript engine and JavaScript runtime environment. But because these topics are often confused, let’s summarize them together.

The JavaScript engine translates your script into runnable machine code instructions so it can be executed by the CPU of the host machine. The engine translates scripts at runtime on the fly. Your code won’t be compiled unless you run it.

The JavaScript runtime environment provides your scripts with utility libraries which can be used during execution. It’s your script that references these libraries. The engine itself doesn’t depend on them.

The cool thing is the JavaScript engine implementation is totally independent of the runtime environment. Engines aren’t developed with any particular environment in mind.

Java Analogy

While the JavaScript engine does the similar job to the Java compiler, the work done by the JavaScript runtime environment can be compared to the work done by the Java Classloader.

There’s a real-life example which demonstrates this approach is working.

You can find the V8 engine both in Chrome browser and NodeJS. One engine successfully utilized in two environments created for totally different uses.


What should you already know?

We started the introduction with the JavaScript engine as a basic element. Then we moved to the components and features of the JavaScript runtime environment. We mentioned the Event loop, Events, and Event handler queue. At the end, you could see the comparison and summary of the JavaScript engine and runtime environment.

Now it’s your turn. Would you like to read more about discussed elements of the JavaScript runtime environment? I’d love to know your thoughts, so please go ahead and leave them in the comments. If you find the article useful, please share it with your colleagues and other developers.


2 Replies to “The JavaScript runtime environment”

Leave a Reply