Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the internal principle of JavaScript?

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article to share with you is about JavaScript internal principle is how, Xiaobian think quite practical, so share to everyone to learn, I hope you can read this article after some harvest, not much to say, follow Xiaobian to see it.

profile

Javascript is a strange language, some people like it, some people hate it. It has many unique mechanisms that do not exist in other popular languages, and there is no corresponding mechanism, and the obvious one is the execution order of code.

Understanding the browser environment, what it consists of, and how it works will allow us to write JS with more confidence and be prepared for potential problems that may arise.

JavaScript engine

The most popular JavaScript engine is V8, which is written in C++ and used by Chrome-based browsers such as Chrome, Opera and even Edge. Basically, this engine is a program that converts JS into machine code and executes the result on the computer's central processing unit (CPU).

compilation

When a browser loads a JS file, V8's parser converts it into an abstract syntax tree (AST). This tree is used to generate an interpreter for bytecodes. Bytecode is an abstraction of machine code that can be executed by compiling into non-optimized machine code. V8 executes it in the main thread, while the optimizing compiler TurboFan does some optimizations in another thread and generates optimized machine code.

This pipeline is called just-in-time (JIT) compilation.

call stack

JavaScript is a single-threaded programming language with only one call stack. It means that our code executes synchronously. Whenever a function runs, it will run completely before any other code runs.

When V8 calls JS functions, it must store runtime data somewhere. A call stack is a location in memory made up of stack frames. Each stack frame corresponds to a function that has not yet been called. The stack structure consists of the following:

local variables

argument Parameter

return address

If we execute a function, V8 pushes the frame to the top of the stack. When we return from a function, V8 jumps out of frame.

As shown in the example above, a frame is created on each function call and deleted in each return statement.

Everything else is dynamically allocated into a large unstructured block of memory called a heap.

Heap

Sometimes V8 compiles without knowing how much memory an object variable needs. All memory allocations for such data occur in the heap. Objects on the heap continue to exist after exiting the function that allocates memory.

The V8 has a built-in garbage collector (GC). Garbage collection is a form of memory management. It acts like a collector, trying to free up memory occupied by objects that are no longer in use. In other words, when a variable loses all references, GC marks that memory inaccessible and frees it.

We can explore the heap by creating snapshots in Chrome Developer Tools.

Each JS object instantiated is grouped under its constructor class. Groups in parentheses indicate native constructors that cannot be called directly. You can see that there are many (compiled code) and (system) examples, but there are also some traditional JS objects, such as Math, String, Array, etc.

browser runtime

V8 can execute JS synchronously using a call stack according to the standard. However, we need to render the UI and handle user interaction with the UI. In addition, we need to handle user interaction when making network requests, but we can't do anything about it. How do we achieve concurrency when all code is synchronized? Thanks to the browser engine.

The browser engine is responsible for rendering pages with HTML and CSS. In Chrome it is called Blink. It is a fork of WebCore, and Blink is a layout, rendering, and document object model (DOM) library. Blink is implemented in C++ and provides DOM elements and events, XMLHttpRequest, fetch, setTimeout, setInterval and other Web APIs that can be accessed through JS.

Consider the following example with setTimeout(onTimeout, 0):

As you can see, the browser first pushes the f1() and f2() functions onto the stack and then executes onTimeout. So how does the example above work?

concurrency

Immediately after the setTimeout function executes, the browser engine places setTimeout's callback function into an event table. It is a data structure that maps registered callbacks to events, in our case the onTimeout function to timeout events.

Once the timer expires, in this case, we set the delay to 0 ms, trigger the event immediately, and place the onTimeout function in the event queue (aka callback queue, message queue, or task queue). An event queue is a data structure consisting of callback functions (tasks) to be processed in the future.

Last but not least, the event loop (an ever-running loop) checks whether the call stack is empty. If so, the first callback added from the event queue is executed, moving to the call stack.

Processing of the function continues until the call stack is empty again. The event loop then handles the next callback in the event queue, if any.

Note the order in which onResolve1, onResolve2, and onTimeout callbacks are executed.

blocking and non-blocking

Simply put, all JS code is considered blocking. While V8 is busy processing stack frames, the browser gets stuck and the UI of the application gets blocked. Users will not be able to click, navigate, or scroll. Until V8 finishes its work, it will not process responses from network requests.

Imagine if we parsed images in a program running in a browser.

In the example above, the event loop is blocked. It cannot handle callbacks in the event/job queue because the call stack contains this frame.

The Web API gives us the possibility to write non-blocking code via asynchronous callbacks. When calling functions like setTimeout or fetch, we delegate all the work to the C++ native code, which runs in a separate thread. Once the operation is complete, the callback is placed in the event queue. Meanwhile, V8 can continue executing JS code.

Using this concurrency model, we can handle network requests, user interactions with the UI, and so on without blocking JS execution threads.

For every developer who wants to be able to solve complex tasks, understanding what the JS environment consists of is crucial. Now that we know how asynchronous JavaScript works, the roles of call stacks, event loops, event queues, and job queues in its concurrency model.

As you might have guessed, there is still a lot of work to be done behind the V8 engine and browser engine. However, most of us just need a basic understanding of all these concepts.

The above is what the internal principle of JavaScript is, Xiaobian believes that some of the knowledge points may be what we see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report