Code (JavaScript) Step

Tahsim Ahmed
Tahsim Ahmed
  • Updated

Custom Code - JavaScript Step

The code step allows you to write and execute JavaScript (ES6) code within your assistant.

Some use cases of a JavaScript step include JSON data manipulation, variable and entity data processing, and last_utterance variable handling. 

Using assistant variables in your code

The code step automatically allows for all of your assistant variables to be used within the code step. To use variables within the code step, simply type the name of the variable, there is no need to declare a new variable.

Example: if there is an assistant variable called score, in the code step to update the score by 1 you just write: score = score + 1;

Screenshot 2023-08-15 at 10.33.08 AM.png

Standard paths

The code step has two standard paths: Default and Failure. The Default path will be followed if your code is successfully run, and the Failure path will be followed if your code fails to run or errors during execution.

Custom paths

It is possible to conditionally branch the flow based on code. You can add up to 10 custom paths in a code step, and give a custom name for each path.

To go down a path, simply call return "path_name" within the code. If nothing is returned, it will use the Default path.

Example: there are two custom paths: "victory", "defeat", the code would look like:

if (score > 100) { 
return "victory"
} else if (score < 0) {
return "defeat"
}
// otherwise it will go down the Default path here

Screenshot 2023-08-15 at 10.42.36 AM.png

FAQ

Which JavaScript Engine is used?

V8 JavaScript Engine.

What JavaScript version is supported?

The Code Step supports ES6.

Are there any Code Step constraints to consider?

Some constraints to consider when using the Code Step include:

  • Code Steps cannot be used to make requests to external servers so cannot be used to call external APIs. Alternatively, you can use the API Step to pull or push data between your Voiceflow agent and a third-party system.
  • Code Steps do not currently support importing modules. Alternatively, you can use the Custom Action step to reference code outside of your Voiceflow agent.
  • Code Steps cannot be used to create new variables. Any variables that you want to use after the Code Step is executed must already exist before being referenced in the Code Step.

Why do I get a TypeError debug message when I test a Code Step using the prototype tool?

Currently, if an existing Voiceflow variable is not set by the time the Code Step begins executing, the value of that variable is 0. e.g. if the Code Step attempts to execute a String method on a variable that is not yet set, a TypeError will occur.

Was this article helpful?

4 out of 21 found this helpful

Have more questions? Submit a request

Comments

0 comments

Please sign in to leave a comment.