- Anatomy of a Sheet Worker
- Events, and watching Attributes
- Variables – How to Name Things
- Arithmetic in Sheet Workers
- What If? in Sheet Workers
- Logging in the Browser Console
- Strings, Arrays, and Loops
- Asynchronicity and Things to Avoid With Loops
- Changes and the eventInfo Object
- Action Buttons
- setAttrs and Saving Attributes
- A Sheet Worker Reprise
- Castle Falkenstein Design – Sheet Workers
- The Perils of Sheet Worker Functions
- The Script Block and Identifying Characters
- Arrays and Dropdowns
- Undefined and Other Error Values
- The Ternary Operator – The One-Line If
- Template Literals
- Functions and the Fat Arrow
- Strings in Sheet Workers
An If Statement In One Line
You have to do something like this a lot:
Your carrying capacity is 10lb per point of strength up to 15 and 20lb per point of strength above that. That calculation takes a lot of code and can be simplified to a single line using a ternary operator.
That looks complicated, but the structure of a ternary operator is simple:
The =, ?, and : are each very important – they split the code into sections.
- The result is a variable, and it can be defined with const or let as normal
- The if statement must produce a true or false result (actually truthy or falsy)
- If true, use the result after the ?
- If false, use the result after the :
So the ternary operation has a Condition, True, and False section.
If you want to calculate multiple values, or use the if statement for branching, use a normal if statement. But if you are setting a single value, ternary operators are very streamlined.
Each value of the ternary operator can itself be a separate expression or even function. You can even nest extra ternary operators inside each of the branches of the code above.
For example, let’s say your carry capacity is 50lb over str 20 as well, you could do this:
When the code has too many branches, it can get too complex to read and at that point, it is better to use a standard if construction. You want your code to be easy to read later. In this case, that would look like this:
You don’t need to use ternary operators. The if statement above works fine. Ternary operators are just a handy tool to use to make your code more compact.
The ternary operator is divided into sections by =, ? and :. All of these must be present. You cannot do this:
This will trigger an error because there is no false result. This will work: