Browse the docs

Run JavaScript

Runs a JavaScript function body inside Switchboard, with your variables as `vars`, and returns its result.

Run JavaScript script

Details #

Runs script in a sandboxed JavaScriptCore context inside Switchboard. It is fast and needs no permissions, because it cannot touch anything outside the macro: no network, no files, no apps.

The script is the body of a function. Your macro's variables arrive as the object vars. Whatever you return is the step's output, as real data (a number stays a number, an object stays an object). If into is set, the variable gets that value. A script that returns nothing (or undefined or null) gives null.

console.log(...) lines appear in the trace row's note, joined with |.

For work that needs apps, files or tools, use Run shell script, Run JXA script or Run Python script.

Parameters #

ParameterTypeRequiredValuesWhat it does
scripttextYesRequired. The function body. {{ }} is not replaced in this script; read values from vars instead.
intotextThe variable that receives the returned value.
sampleany valueWhat into holds during a dry run.
timeoutnumberSeconds before the script is stopped.

Every step also accepts label, onFailure, timeout and dryRunSafe.

Examples #

Example
Do
  1. Set prices to 4, 8, 15
  2. Run JavaScript “const sum = vars.prices.reduce((a, b)…”
  3. Show “Total {{stats.sum}}”
Open in Switchboard to try it

Gotchas #

  • Dry run. Not run: into gets sample, or an empty string.

  • Timeout. A runaway loop is stopped at the step's time limit (10 s unless set) and the step fails with "the script ran past its N s timeout".

  • Errors. A thrown error or a syntax error fails the step with the message and the line number in your script.

  • The result must be JSON-compatible. Functions and undefined values inside objects are dropped.

  • Variables are copied in. Changing vars does not change the macro's variables; return the new value and use into.

See also #

Run JXA script, Run shell script, Set variable