If

The if() function allows the creation of conditional logic statements

The generic form for conditional logic is if (condition) {return value}

As a general rule, {} denotes the parts of expressions to be executed - the ‘then’ part that is returned when the condition is met

e.g. You want to know who is getting close to retirement age and may possibly leave the company in the near future

Use if (node.age > 55) {"Risk"}; this will return Risk if the age of the current node is over 55

Including else {} adds a contingency to the conditional logic statement in the generic form if(condition) {return value} else {return value}

In the same example, if the current node (employee) is 55 or younger than 55, "No Risk" will be returned

if (node.age > 55) {("Risk");} else {("No Risk");}

This syntax can be shortened using the a ? b : c (ternary) syntax

a ? b : c can replace if () {} else {}

node.age > 55 ? "Risk" : "No Risk"

image

See case() and .is() for an alternative to if() statements that provides improved Gizmo calculation performance

e.g. the above expression may be written with case() and .is() like this:

node.case(is.prop("age", is.gt(55)), "Risk" , "No Risk");

Operators in if statements

Operators can be used in the expression to add nuance to the condition

e.g. if (node.country == "UK" && node.depth < 3) {"UK Management"}

Multiple Else If Statements

If you need to evaluate a property to provide multiple {return value} options

You can build expressions nesting multiple else if {} statements

e.g. To classify performance ranking data; 8-10 as A, 6-8 as B, 4-6 as C and 0-4 as D

You could use

  • A.

    if (node.performanceranking > 8) {
    ("A");
    } else if (node.performanceranking > 6) {
    ("B");
    } else if (node.performanceranking > 4) {
    ("C");
    } else {
    ("D");
    }
    

However, while this will work, it is an inefficient approach as it evaluates the node multiple times for the same operation which causes performance loss

This will be discussed further in Optimising tips

A more efficient approach is use variable declaration which assigns a value to the reference so the expressions can refer to the value without repeating evaluation

This takes the generic form var [variable name] = [value]

In this example the variable pr has been assigned the value of node.performanceranking so would equal 8.2

image

  • B.

    var pr = node.performanceranking;
    if (pr > 8) {
      ("A");
    } else if (pr > 6) {
      ("B");
    } else if (pr > 4) {
      ("C");
    } else {
      ("D");
    }
    

image

In this example it can be seen that the evalualtionDuration reported is longer for the expression with multiple evaluations of the node

results matching ""

    No results matching ""

    results matching ""

      No results matching ""