The Basics of How JavaScript Works


JavaScript is a client-side scripting language that runs in most browsers and is widely used to make dynamic web pages. It is also used to validate data and to support external applications such as Flash, PDFs and widgets on the web.

It is very important to know the basics of how JavaScript works in order to use it effectively. For example, it is critical to understand how the JavaScript engine works to be able to write non-blocking JavaScript apps.

The JavaScript engine is a rudimentary compiler that takes the source code and compiles it into an intermediate representation (IR) which is known as bytecode, and then feeds this to an interpreter. The interpreter then converts this bytecode to machine code and then finally executes the bytecode on the CPU.

During the IR generation, the compiler makes changes in the source code that will allow the interpreter to generate a human-readable syntax. This syntax is very different from the machine-readable bytecode, and so the compiler has to work hard to translate it into machine code.

In order to be able to generate this syntax, the compiler must understand a number of things about the underlying architecture. These include the call stack, the DOM, and how JavaScript interacts with them.

The call stack is the set of functions that the JavaScript engine calls out to when it wants to do something on a page. This is where a lot of complex UI work happens, and if you don’t understand how the call stack works you could have serious issues with your app.

One problem with the call stack is that when it gets a big load of function calls, it can get blocked and take a long time to process. This is a common problem, especially with JavaScript code that has lots of complex functions, and can lead to a bad user experience.

To resolve this, the engine has a feature called an event loop that spawns these long-running tasks to separate threads. Then it enqueues a callback function on the main thread when the task is complete. This way, the JavaScript engine can handle long-running operations without blocking the JS main thread.

While the event loop is a great feature, it is important to understand that this is only a partial solution. There are other things that the JS engine can do to help improve performance and ensure that long-running tasks aren’t blocking the JS main thread.

Another thing that the JS engine can do is to offload long-running tasks to other threads on your browser or Node. These tasks can be anything from sending HTTP requests to listening for a response. When these things are spawned on separate threads, they aren’t blocked by the JS engine and can be handled much faster.

Generally, the JS engine will load and run your code in the order that it appears on the page. You should avoid placing your JS code before the HTML and CSS on your page because it may cause errors.