Variables and expressions

Use variables and expressions to define input values and control logic in workflow blocks. In most blocks, expressions specify conditions and control execution flow.

You must use JavaScript ECMAScript 2020 (ES2020) syntax to specify variables and expressions. For more information about JavaScript ECMAScript 2020, see ECMAScript® 2020 Language Specification.

You can define variables and expressions in several areas of the workflow editor: in the variable definition fields of the Start block, in some block variables, and in the object editor. This topic contains several examples to help you get started.

Variables and values

Variables and values are building blocks for expressions. Use the following table to find example values for each type of variable that you can specify:

Table 1. Variable types and example values
Variable type Description Example values
String Must contain text that is enclosed in quotation marks ("").

For more information, see String.

"Hello_world!"
Password Can contain any text, including numbers and special characters. Passwords are hidden by default in the Start block.
"Password123!"
Number Must be numeric. Decimal values are allowed.

For more information, see Number.

1234, 3.14, 45.67
Boolean Must be either true or false, without quotations.
true
false
Array Must be enclosed in square brackets ([]) and can contain elements of any type. These elements can have a mix of any types in the same array, including numbers, strings, arrays, or objects.
[1, "d", [1,2,3]]
Object Enclosed in braces ({}) and consists of key-value pairs. Keys are enclosed in quotation marks (""), and values can be any type: numbers, strings, arrays, or other objects.

For more information, see Object.

Simple object:

{"a": [1,2,3]}

Nested object:


{
  "user": {
    "name": "userName",
    "age": 34,
    "email": "userEmail@example.com",
    "isActive": true,
    "roles": ["developer", "admin"],
    "profile": {
      "location": "London",
      "department": "Sales"
    }
  }
}

              
Enum Defines a fixed list of values of the same type, such as strings or numbers.

In the Start block, use the Define variable type option to create a JSON definition of the enum values.

Set the variable to In and Required to use the enum as an input parameter in an Automation center tile or another workflow. This action makes the enum available as an input block in the calling workflow.

{"type": "string", "enum":
 ["red", "green", "blue"]}
{"type": "string", "enum":
 ["apple","orange","pear"]}
{"type": "string", "enum":
 ["low", "medium", "high"]}
Authentication Stores authentication credentials used in an authkey block variable when type is set to expression.

If you do not want to use an authentication variable that you defined in the Start block, you can specify authentication credentials manually in the block variable by using an expression.

{"username": "user", "password": "pass"}
Any Accepts any type, for example, number, string, array, object.
123, ["x", "y"], {"a": 1}
Custom Used to define complex schemas, such as schemas that are combined by using the JSON oneOf and anyOf keywords.

oneOf example:


{
  "type": "string",
  "oneOf": [
    { "const": "admin" },
    { "const": "user" }
  ]
}
              

anyOf example:


{
  "type": "object",
  "properties":{
    "paymentMethod": {
      "anyOf":[
        {"card": 
{"number": "string",
 "expiry": "string"}},
        {"paypal":
{"email": "string"}},
        {"bankTransfer": 
{"accountNumber": "string",
 "routingNumber": "string" }}
      ]
    }
  }
}
              
Important: Expressions and variables are evaluated only at runtime when the workflow is running. You cannot evaluate expressions and variables when you are designing your workflow in the editor.

Basic expressions

Basic expressions are made up of variables, values, and operators. Use the following table to find example expressions for each type of operator:

Table 2. Operator types and example expressions
Operator type Description Operators or Syntax Example expressions
Arithmetical Apply basic math operations such as addition, multiplication, and finding the remainder. +, *, %
if ($i + 3 == 7)
Equivalence Compare values to determine whether they are equal or not equal. ==,!=
if ($i != 5)
Identicality Test whether data types or values are identical. ===,!==
typeof $A18.result === 'object'
Logical Combine multiple conditions to control the program flow.
  • || for OR
  • && for AND
if ($i != 5 & $p == 2)
Comparison Compare the two values to determine whether one is greater than, less than, or equal to the other.

>, <, >=, <=

if ($i > 6)
Boolean Use a variable directly as a condition. If the variable is set, it evaluates to true, if not set, it evaluates to false. <variable_name>
if ($testvariable1)
Conditional Use to define logic that runs one action if a condition is true and a different action if the condition is false. if <condition> then <action A> else <action B>

{
  "operator": "conditional",
  "condition": "status == 'active'",
  "ifTrue": "Send email",
  "ifFalse": "Log entry"
}

if (status === 'active') {
  sendEmail();
} else {
  logEntry();
}
              
Subconditional Use methods or properties within a condition to evaluate specific criteria. .includes(), .length or others.
$fullname.includes("Smith")

Advanced expressions

Use advanced JavaScript expressions to simplify complex logic, improve workflow readability, and help ensure correct execution order.

The following sections provide example expressions to get you started. For more methods and syntax details, refer to the ECMAScript® 2020 Language Specification.

Assigning multiple variable values together

To assign values to multiple variables simultaneously, you can use array restructuring. In the following expressions, four values are assigned to variables individually:


$result = "Hello, World!";
$result2 = "String2";
$result3 = "String 3";
$result4 = "String 4444444444";
    

By using array restructuring, you can combine these assignments into a single expression, as shown in this example:


[$result, $result2, $result3, $result4] = ["Hello, World!", "String2", "String 3", "String 4444444444"];
    
Formatting complex logical expressions

To help ensure that a complex expression is evaluated in the correct order, use parentheses to logically group the relevant clauses in the expression, as shown in this example:

 ($Upgrade_This_Month && (($Current_Year < $File_Year) ||
                                   ($Current_Year == $File_Year && 
                                    $Current_Month < $File_Month))) 

This expression returns true when: $Upgrade_This_Month is true, and either:

  • $Current_Year is less than $File_Year,

OR

  • $Current_Year equals $File_Year and $Current_Month is less than $File_Month.
Assigning values based on ternary operators

This expression checks whether the $result object has a property that is called quantity:

$result.hasOwnProperty("quantity") ? $result.quantity : 0;
  • If true, the expression evaluates to the value of $result.quantity.
  • If false, the expression evaluates to 0.
Listing keys in a JSON object

Use the Object.keys() method to extract all the keys from a JavaScript object that contains key-value pairs, as shown in this example:


var $someObj = {
  dogs: 3,
  cats: 5,
  whales: 1
};
var keys_only = Object.keys($someObj);
 // keys_only evaluates to ==> ["dogs", "cats", "whales"]
    
Summing and averaging values in arrays

To loop through elements of an array and return the total or average value of all elements, you can use two methods: .forEach() and .reduce().

The syntax of the .forEach() method is:

array.forEach(function(currentValue, index, arr), thisValue)

For more information about how the .forEach() method works, see Array.prototype.forEach().

The syntax of the .reduce() method is:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

For more information about how the .reduce() method works, see Array.prototype.reduce().

Summing all elements in an array

This example shows how you can sum array elements by using the .forEach() method:


var nums = [2, 4, 6, 8];

var sum; // value to calculate 
var sum = 0; // initial value 
nums.forEach(eachNumber => {
  sum = sum + eachNumber;
});
print(sum); // Returns ==> 2+4+6+8 = 20.
    

This example shows how you can sum array elements by using the .reduce() method:


var nums = [2, 4, 6, 8];
var sum = nums.reduce((a, b) => a + b, 0);
print(sum) // Returns ==> 2+4+6+8 = 20.
    
Calculating the average of all elements in an array

This example shows how you can calculate the average of all the elements in an array by using the .forEach() method:


var nums = [2, 4, 6, 8];
var avg; // what we want to calculate 
avg = 0; // initial value
nums.forEach(eachNumber => {
  avg = avg + eachNumber;
});
// Divide by number of things 
var avg = avg / nums.length; 
print(avg) // Returns ==> 20/4 = 5.
    

This example shows how you can calculate the average of all the elements in an array by using the .reduce() method:


var nums = [2, 4, 6, 8];
var avg = nums.reduce((a, b) => a + b, 0) / nums.length;
print(avg); // Returns ==> (2+4+6+8)/4 = 5.
    
Using the .reduce() method with object properties
This example shows how to use the .reduce() method with objects properties instead of primitive values like numbers, strings, and booleans.

Schema definition:

{
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "name": {
                 "type": "string"
             },
             "age": {
                 "type": "number"
             }
         },
         "required": ["name", "age"]
    }
}
 
Defined array:
$people = [
{ name: "John", age: 35 },
{ name: "Peter", age: 44 },
{ name: "Little Robbie", age: 64 },
{ name: "Alfredo", age: 12 }
];
Calculate average age in the group:
var averageAge = $people.reduce((a, b) => a.age + b.age, 0) / $people.length;
print(averageAge); // Returns: 38.75
Reduce the average to the nearest lesser whole number by using Math.floor() to return an integer result instead of a float number:
var averageAge = Math.floor($people.reduce((a, b) => a.age + b.age, 0) / $people.length);
print(averageAge); // Returns: 38

For more information about how the Math.floor() method works, see Math.floor().

Concatenating strings and variables

To concatenate strings and variables in expressions, use either the JavaScript + operator or template literals.

Using the JavaScript + operator

Use the JavaScript + operator to concatenate strings and variables and construct simple, single-line expressions, such as this example:

'Hello' + ' ' + 'World' // Returns: "Hello World"
Using template literals

Use template literals for multi-line or more complex pieces of text where you want to insert variable values. In a template literal expression, wrap the string in back ticks (``), and then inside the string you can use variables in a ${<variable_name>} format, as shown in this example:

const name = "User1";const greeting = `Hello, ${name}! Welcome to IBM Concert Workflows®.`;console.log(greeting); 
Manipulating strings

Use string methods such as .split() and .join() to extract or format text from paths or structured data.

Splitting delimited strings into arrays

Use the .split() method to convert a string into an array based on a specified delimiter, such as "/", as shown in this example:


var $path = "animal/cat/tom";
var $splitPath = $path.split("/");

print($splitPath); // Returns: ["animal", "cat", "tom"]
print($splitPath[$splitPath.length - 1]); // Returns: "tom"
      

For more information about how the .split() method works, see String.prototype.split().

Converting array elements into strings

Use the .join() method to convert an array into a single string with a custom separator, as shown in this example:


var $stuff = ["animal", "cat", "tom"];
print($stuff.join(" AND")); // Returns: "animal AND cat AND tom"
      

For more information about how the .join() method works, see Array.prototype.join().