Take advantage of more JavaScript features in your Packs

Hi Pack Makers - As you may recall Packs run in a custom JavaScript runtime, where you have access to the core language features but not any of the browser-or-Node-specific libraries (window, fs, etc). The JavaScript standard (ECMAScript) is always evolving, and I’m happy to announce that we’ve updated the Packs runtime to be compatible with the version ES2022.

There is no need to update your existing Packs (it’s fully backwards compatible) but it does allow you to take advantage of some newer features of the JavaScript language in your Packs. Here are some of my favorites:

replaceAll()

A “gotcha” with the normal String replace() method is that it only replaces the first instance of the search string.

"banana".replace("a", "o") --> "bonana"

The previous workaround was to use a regular expression for the search string instead, but with the new replaceAll() method you can just keep on using normal strings.

"banana".replaceAll("a", "o") --> "bonono"

at()

When working with arrays (or strings) it’s pretty common to need to look at the first or last value. Getting the first value was easy but getting the last value was always a bit of a pain to type out.

let first = fruits[0];
let last = fruits[fruits.length - 1];

With the new .at() method, you can use negative indexing to reference items from the end of the array.

let first = fruits.at(0);
let last = fruits.at(-1);

Conditional assignment

It’s pretty common to need to assign a default value to a variable if one hasn’t already been assigned. There two pretty common ways to accomplish that:

if (!order.fruit) {
  order.fruit = "apple";
}

// or ...

order.fruit = order.fruit ?? "apple";

Both approaches are a bit wordy, and have other shortcomings in certain situations. The new conditional assignment operator condenses it all down:

order.fruit ??= "apple";

Are there any features your excited about? Check out the full list of ES2021 and ES2022 features you can now use in your Packs.

10 Likes

Does this mean that a replace all formula might be coming natively to coda?

The two aren’t directly related @Samuel_Langford, but I’ll pass along the suggestion!

1 Like

Hi @Samuel_Langford - Inspired by your comment I went ahead and added a SubstituteAll formula to the Coda formula language:

SubstituteAll("banana", "a", "o") = "bonono"

Let me know what you think!

9 Likes

This is amazing! Exactly what I needed. Thank you!

Thank you, Eric. I’ve yenned for this formula for a while now! Very useful.

1 Like