Skip to main content

If Expressions

If expressions allow us to select a value based on a boolean (true or false) value. For example, the expression:

if x > 10 then "big" else "small"

will evaluate to the string "big" if x is greater than 10 and will evaluate to the string "small" otherwise. Let's look at another example of an if expression:

foreach device in network.devices
let dcName = if prefix(device.name, 3) == "atl"
then "ATLANTA"
else "PHOENIX"
select { device: device.name, dataCenterName: dcName }

In this example, if the field name in device's first 3 letters are "atl", then dcName is "ATLANTA", otherwise dcName will be "PHOENIX". Either way, dcName will always be set to a string. Note: the two branches of an if expression must contain values of the same type, in both of these cases, string.

Here are some more examples:

  • daysInYear(year) = if isLeapYear(year) then 366 else 365;
  • maximum(x, y) = if x > y then x else y;.
  • makeEven(x) = if x % 2 == 0 then x else x * 2;. A function that returns the argument if it was even, or returns the argument multiplied by two if it was odd.

A note for users familiar with other programming languages. Many programming languages, such as Python and Java, have if statements that differ from NQE's if expressions. In those languages, if statements control execution of two different blocks of statements. In contrast, NQE's if expressions chooses between two different expressions. However, languages ( e.g. Python and Java) also typically have "ternary conditional" expressions that are analogous to NQE's if expression. The following examples are equivalent to NQE's if boolean then thenValue else elseValue:

  • In Python: thenValue if boolean else elseValue.
  • In Java: boolean ? thenValue : elseValue.