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:
| Variable type | Description | Example values |
|---|---|---|
| String | Must contain text that is enclosed in quotation marks ("").
For more information, see String. |
|
| Password | Can contain any text, including numbers and special characters. Passwords are hidden by default in the Start block. |
|
| Number | Must be numeric. Decimal values are allowed.
For more information, see Number. |
|
| Boolean | Must be either true or false, without quotations. |
|
| 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. |
|
| 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:
Nested object:
|
| 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. |
|
| 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. |
|
| Any | Accepts any type, for example, number, string, array, object. |
|
| Custom | Used to define complex schemas, such as schemas that are combined by using the JSON oneOf and anyOf keywords. |
oneOf example:
anyOf example:
|
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:
| Operator type | Description | Operators or Syntax | Example expressions |
|---|---|---|---|
| Arithmetical | Apply basic math operations such as addition, multiplication, and finding the remainder. | +, *, % |
|
| Equivalence | Compare values to determine whether they are equal or not equal. | ==,!= |
|
| Identicality | Test whether data types or values are identical. | ===,!== |
|
| Logical | Combine multiple conditions to control the program flow. |
|
|
| Comparison | Compare the two values to determine whether one is greater than, less than, or equal to the other. |
>, <, >=, <= |
|
| 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> |
|
| 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> |
|
| Subconditional | Use methods or properties within a condition to evaluate specific criteria. | .includes(), .length or others. |
|
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 togetherTo 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_Yearis less than$File_Year,
OR
$Current_Yearequals$File_Yearand$Current_Monthis less than$File_Month.
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.
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"]
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().
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.
.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().
To concatenate strings and variables in expressions, use either the JavaScript + operator or template literals.
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);
Use string methods such as .split() and .join() to extract or format text from paths or structured data.
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().
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().