If

An if line conditionally executes some lines of code depending on a variable, function call or expression.

Parts

  • The condition
  • Then and else

The condition

The condition is a boolean variable, a function returning a boolean value or an expression resulting in a boolean value.

The condition is either true or false. If true, the then-part is executed. If false, the else-part is executed.

For more information, see Boolean and Boolean expression and Function call.

Then and else

The then and else parts follow the condition; first the then-part and then the else-part.

Example

In this example, if a is equal to b, then f(x) is executed. If not, then g(x) is executed.

if(a = b){
    f(x);
}else{
    g(x);
}

Shortening the else-part

If an else-part contains only one line, and that is another if, then the the else-if can be shortened.

For example,

if(a = b){
    f(x);
}else{
    if(a = c){
        g(x);
    }else{
        h(x);
    }
}

Can be shortened to,

if(a = b){
    f(x);
}else if(a = c){
    g(x);
}else{
    h(x);
}