Conditionals
Control program flow with if/else, switch, ternary, elvis, and safe navigation operators
BoxLang provides powerful conditional expressions and control flow statements to direct program execution based on runtime conditions. From traditional if/else blocks to modern operators like elvis (?:) and safe navigation (?.), BoxLang offers multiple ways to handle conditional logic elegantly.
📋 Table of Contents
💻 Conditionals in Code
Let's explore conditional operations with practical examples:
🔍 Comparison Operators
Conditional statements evaluate to true or false only. BoxLang provides both symbolic and word-based operators for comparisons.
Operator Reference
==, ===
EQ, EQUAL, IS
Equal to
a == 1
!=, !==
NEQ, NOT EQUAL
Not equal to
a != 2
>
GT, GREATER THAN
Greater than
a > 2
>=
GTE, GREATER THAN OR EQUAL TO
Greater than or equal
a >= 1
<
LT, LESS THAN
Less than
a < 2
<=
LTE, LESS THAN OR EQUAL TO
Less than or equal
a <= 1
CONTAINS
-
String/array contains value
str CONTAINS "test"
DOES NOT CONTAIN
-
Does not contain value
str DOES NOT CONTAIN "test"
Basic Comparisons
Type Checking Functions
Many BoxLang functions return true or false, making them ideal for conditional statements:
Truthy and Falsy Values
BoxLang evaluates certain values as boolean:
🔀 If, Else If, & Else
Why do we have conditional statements? Most often it's to control conditional instructions, especially if / else if / else expressions. Let's write an example by adding a method to our PersonalChef.bx class:
Try this example using 5, 7, 8 and 9 for the values of minutes.
When the minutes is 5, here is how the execution goes: Is it true that 5 is less than 7? Yes, it is, so print out the line
The water is not boiling yet..When the minutes is 7, it goes like this: Is it true that 7 is less than 7? No. Next, is it true that 7 is equal to 7? Yes, it is, so print out the line
It's just barely boiling.When the minutes is 8, it goes like this: Is it true that 8 is less than 7? No. Next, is it true that 8 is equal to 7? No. Next, is it true that 8 is equal to 8? Yes, it is, so print out the line
It's boiling!.
Lastly, when total is 9, it goes:" Is it "true" that 9 is less than 7?
No. Next, is it true that 9 is equal to 7? No. Next, is it true that 9 is equal to 8? No. Since none of those are true, execute the else and print the line Hot! Hot! Hot!.
An if block has:
One
ifstatement whose instructions are executed only if the statement is trueZero or more
else ifstatements whose instructions are executed only if the statement is trueZero or one
elsestatement whose instructions are executed if noifnorelse ifstatements were true
Only one section of the if / else if / else structure can have its instructions run. If the if is true, for instance, BoxLang will never look at the else if. Once one block executes, that’s it.
❓ Ternary Operator
The ternary operator provides a compact one-line conditional expression: condition ? trueValue : falseValue
Syntax
The condition is evaluated. If true, the first expression is returned; if false, the second expression is returned.
Basic Examples
Nested Ternary (Use with Caution)
Best Practice: Avoid deeply nested ternary operators as they become hard to read and debug. For complex conditions with multiple branches, use if / else if / else or switch statements instead.
Practical Uses
🎸 Elvis Operator
The elvis operator (?:) provides elegant null-coalescing and default value assignment. It returns the left operand if it exists and is not null, otherwise returns the right operand.
Syntax
If value is null or undefined, defaultValue is used. Otherwise, value is used.
Basic Examples
Before Elvis: The Old Way
Before the elvis operator, you had to use verbose checks:
Practical Applications
Elvis vs Ternary
Best Practice: Use elvis (?:) for null-checking and default values. Use ternary (? :) for conditional logic based on comparisons or boolean conditions.
❓ Safe Navigation Operator
The safe navigation operator (?.) allows you to safely navigate nested structures without throwing key not exists exceptions. If any part of the chain is null or undefined, the entire expression returns undefined instead of throwing an error.
Syntax
If object or property is null or undefined, the expression returns undefined instead of throwing an error.
Before Safe Navigation: The Old Way
Basic Examples
Practical Applications
Chaining with Other Operators
Error Prevention
Best Practice: Use safe navigation (?.) when accessing properties that might not exist. Combine with elvis (?:) to provide default values for missing data. This pattern is especially useful for API responses, configuration files, and optional struct properties.
🔀 Switch, Case, & Default
The switch statement evaluates a single expression and executes different code blocks based on matching case values. It's ideal when you have multiple discrete values to check against a single variable.
Syntax
Structure
One
switchstatement - Evaluates a single expression onceMultiple
casestatements - Define values to match againstOptional
break- Exits the switch block (prevents fall-through)One optional
default- Executes if no case matches
Basic Example
Multiple Cases (Fall-Through)
Break Statement
Best Practice: Always include curly braces {} for case blocks and use break statements unless you specifically want fall-through behavior. Forgetting break is a common bug!
Practical Examples
When to Use Switch vs If/Else
🔁 While Loops
The while loop executes a code block repeatedly as long as the conditional expression evaluates to true. It's useful for processing queues, polling, and iterating when the number of iterations isn't known in advance.
Syntax
Basic Example
Practical Examples
Do-While Loop
BoxLang also supports do-while loops, which execute the block at least once before checking the condition:
Infinite Loops and Break
Caution: Ensure your while loop condition will eventually become false, or use a break statement to exit. Infinite loops without an exit condition will hang your application!
⚠️ Common Mistakes
The == vs = Confusion
== vs = ConfusionThe #1 mistake in conditional statements is confusing assignment (=) with comparison (==).
=
Assignment - "Put value on right into variable on left"
x = 5
==
Comparison - "Is left equal to right?"
x == 5
Other Common Pitfalls
📚 Best Practices Summary
✅ Use appropriate operators:
if/elsefor complex logic,switchfor discrete values, ternary/elvis for simple assignments✅ Always use
==for comparisons, never=in conditions✅ Use safe navigation (
?.) to avoid null pointer errors✅ Combine elvis (
?:) with safe navigation for elegant default values✅ Include
breakin switch cases unless you specifically want fall-through✅ Add curly braces
{}around all code blocks for clarity✅ Avoid deeply nested ternary operators - use
if/elsefor complex conditions✅ Ensure while loops have exit conditions to prevent infinite loops
✅ Use meaningful variable names in conditions for readability
✅ Format conditions consistently with spaces:
if ( condition )notif(condition)
🔗 Related Documentation
OperatorsProgram StructureException ManagementLast updated
Was this helpful?
