Code Style

Throughout Espruino we tend to use a code style very similar to the K&R-like 1TBS style), with a relaxation on the need for braces around single-line blocks.

For example:

const MY_CONSTANT = "Hello";

function myFunction() {
  if (1==1)

  if (1==1) {
  } else {
  var obj = {

class MyClass {
  test() {

var classInstance = new MyClass();

function MyClass2() {
MyClass2.prototype.test = function() {

The basic rules are:

These is also the same coding style used for the firmware's C code

Other Suggestions

When pretokenisation is enabled (in 2v21 and later), strings will be stored as raw data and only referenced (so that their contents are loaded from flash on demand). This is very fast and memory efficient.

// - Very efficient in 2v21 with pretokenisation enabled - string is referenced
// in flash and only read when needed.
// - Uses RAM in 2v20 and earlier (or without pretokenisation)
const mydata = atob("GBgCAAAAAAAAAAQA....AAAAAAAAAAAAA");
// mydata is a string

const myarray = new Uint8Array(E.toArrayBuffer(atob("SGVsbG8gd29ybGQ=")));
// 2v21+ myarray is a read-only Uint8Array that references the data in Flash memory
// pre-2v21 it's a normal Uint8Array in RAM

// doesn't use RAM until called
function getMyData() {
// uses 18 blocks of memory, slow to access
var a = new Array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]);

// uses 4 blocks of memory, fast to access
// (in this case, stores numbers in range 0..255)
var a = new Uint8Array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
// Uses lots of RAM, hard to read
function draw(text,alignLeft,alignRight,isUpsideDown) {

// Function uses less RAM, easier to read and extend
function draw(text,options) {


For much more detail, check out the Espruino Performance page

Code size

Code written this way is reasonably compact, and when executing from source code size matters

Bracket Counting

Each time you press enter, Espruino's command-line interface counts brackets to see if the statement you've entered is complete. If it is, it'll try and execute it. For instance:

if (true) {

is a complete statement, so when you hit enter at the end it'll be executed immediately. However if you type:

if (true) {
else {
  console.log("Oh No!");

Then now we have a problem. Halfway through, Espruino sees that the first if statement is complete and executes, and it's now given a line that starts else { that isn't a valid statement.

The easiest way to fix this is to write code in the style above:

if (true) {
} else {
  console.log("Oh No!");

The IDE is smart enough that if you write code in some other way on the right-hand side of the IDE it'll replace all the newlines with a special newline (Alt-Enter) that doesn't cause execution. However it's a good idea to write code in a style that would allow you to copy and paste it to the left hand side of the IDE if needed.

This page is auto-generated from GitHub. If you see any mistakes or have suggestions, please let us know.