Contact Free trial Login

Flow Control and Scope Operations in DataWeave

You can use the following operators within any DataWeave expression:

Before you begin, note that DataWeave 2.0 is for Mule 4 apps. For a Mule 3 app, refer to the DataWeave 1.0 documentation set in the Mule 3.9 documentation. For other Mule versions, you can use the version selector for the Mule Runtime table of contents.

do

A do statement creates a scope in which new variables, functions, annotations, or namespaces can be declared and used. The syntax is similar to a mapping in that it is composed of a header and body separated by ---. Its header is where all the declarations are defined, and its body is the result of the expression.

This example uses do to return the string "DataWeave" when myfun() is called from the main body of the script.

DataWeave Script:
%dw 2.0
output application/json
fun myfun() = do {
    var name = "DataWeave"
    ---
    name
}
---
{ result: myfun() }

This example uses do to return the string "DataWeave" when the variable myVar is referenced from the main body of the script.

DataWeave Script:
%dw 2.0
output application/json
var myVar = do {
    var name = "DataWeave"
    ---
    name
}
---
{ result: myVar }

Both scripts produce this output:

Output:
{
  "result": "DataWeave"
}

The next example uses do to prepend the string "Foo" to a string (" Bar") that is passed to the test(p: String) function.

DataWeave Script:
%dw 2.0
output application/json
fun test(p: String) = do {
    var a = "Foo" ++ p
    ---
    a
}
---
{ result: test(" Bar") }
Output:
{
  "result": "Foo Bar"
}

if else

An if statement evaluates a conditional expression and returns the value under the if only if the conditional expression is true. Otherwise, it will return the expression under else. Every if expression must have a matching else expression. The following example uses the input { country : "FRANCE" }, which is defined by the myVar variable in the header:

DataWeave Script:
%dw 2.0
var myVar = { country : "FRANCE" }
output application/json
---
if (myVar.country == "USA")
  { currency: "USD" }
else { currency: "EUR" }
Output
{
  "currency": "EUR"
}

else if

You can chain several else expressions together within an if-else construct by incorporating else if. The following example uses the input var myVar = { country : "UK" }, which is defined by the myVar variable in the header.

DataWeave Script:
%dw 2.0
var myVar = { country : "UK" }
output application/json
---
if (myVar.country =="USA")
	{ currency: "USD" }
else if (myVar.country =="UK")
	{ currency: "GBP" }
else { currency: "EUR" }
Output
{
  "currency": "GBP"
}

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub