Inside XS: Scopes
The XS JavaScript engine is unique in delivering modern JavaScript (ECMAScript 2024) to resource-constrained, low-cost microcontrollers. One reason XS can do so much with so few resources is thanks to the careful design of its internal data structures. These data structures represent the current state of the JavaScript runtime, including primitive values and objects.
A new document by Patrick Soquet, architect of XS, introduces the data structures used to represent JavaScript scopes in XS. Scopes are used to implement many essential JavaScript features – including blocks, closures, generators, asynchronous functions – to manage access to values across invocations.
XS Scopes explains how XS represents scopes using four detailed examples.
- One function closing over two variables
- Two functions closing over a single variable
- Returning a new function that closes over a variable
- Generator function closed over a single variable
Async functions handle closures in the same way as generator functions.
Each example starts with a simple JavaScript code fragment that will be familiar to experienced JavaScript developers. That's followed by a step-by-step walk through of the byte code of the example. Each step describes how the byte code changes the stack and the data structures in the XS slot and chunk heaps.
To make these explanations easier to follow, the document begins with an introduction to essential concepts in the XS implementation.
- Virtual machine
- Slots
- Chunks
- Byte code
- Operators
- Stack
- Functions
- Scopes
XS Scopes is essential reading for everyone interested in how XS works. For developers working in JavaScript who have never studied the implementation of a JavaScript engine, it is an accessible look "behind the scenes" at what goes on as XS runs their JavaScript code.