Writing Embedded JavaScript for IoT
Basic syntax of Embedded JavaScript
If you're familiar with JavaScript from working in the web ecosystem, you already know embedded JavaScript. The XS JavaScript engine for embedded provides the same JavaScript language used in web browsers and Node.js (official known as ECMAScript 2023), so there are no new language concepts to learn.
However, if you're an embedded developer without prior experience in JavaScript, the good news is that basic JavaScript syntax is similar to C. To assist C/C++ developers in learning embedded JavaScript, we've dedicated a chapter to this topic in our book. With this guide, you'll be up and running quickly, as it's the only resource specifically written for C/C++ developers looking to learn JavaScript.
Key concepts and features
The key difference between developing with Embedded JavaScript and JavaScript on the web isn't the language, but the hardware running the project. Embedded hardware may be 50 times slower with 200 times less RAM. The consequence of that is that much more of the focus is on optimizing performance and resource use.
Embedded JavaScript stores objects and data in flash memory (ROM) as much as possible to reduce RAM. As a result, many more JavaScript objects are frozen than usual. This is very familiar to developers using functional programming. There's nothing very complicated about working with frozen objects, and it is already part of standard JavaScript.
One of the most unique and powerful features of embedded JavaScript with the Moddable SDK is preloading. This runs parts of your code at build time on your computer. Execution then continues on the embedded devices. Preloading reduces start-up time on the device, allowing embedded JavaScript projects to start running in milliseconds. Preloading also reduces the RAM used by running projects, potentially allowing the use of less expensive chips (with less RAM).
Modular development is crucial for ensuring scalability, especially in the context of large, dispersed teams. To achieve this, the use of standard JavaScript modules (e.g. ESM) is encouraged with the support of Embedded JavaScript. Additionally, unit testing is recommended to reduce dependencies. Embedded JavaScript also enables the implementation of private fields and methods, which allows modules to remain fully hidden, further reducing the risk of unintended dependencies.
Writing code for common IoT devices
Within the Moddable SDK, there are hundreds of focused example applications that demonstrate the use of specific IoT device features. These examples cover a wide range of topics, from graphics to networking to data storage, making them an excellent resource for those who are just starting to explore the possibilities.
Moreover, the Moddable SDK offers consistent APIs across all chipsets, which simplifies the development process. Once a developer has learned how to work with one chipset, they have the foundation to work with all of them.