# A Thing or Two explainer

The aim of this puzzle: Use a ternary operator in place of an if…else statement.

Walkthrough of the solution:
To review, an if…else statement takes this format:

``````if (thisIsTrue) {
doThis
} else {
}
``````

A ternary operator replaces this format with something much shorter:

``````isThisTrue ? doThis : doThisInstead
``````

The code before the `?` is the test. If the test returns ‘true’, then the code after the `?` will execute. If the test returns false, then the code after the `:` will execute. Ternary operators are useful in how they use fewer lines of code than an if…else statement, however they can be more difficult to read.

The x variable uses the pickRandom() function to choose between the number 1 and 2.
There is a `print()` with a ternary inside of it. The test `x === 1` will check if the number is equal to 1. If this is true, it will return `one` to the `print()` statement. If this is false, it will return `two`.

Sample code solution:
(Tap below to reveal)

``````let x = pickRandom(2);
print(x === 1 ? 'one' : 'two');
print(x);
``````

JavaScript Concepts: Ternary Statement, Variable Assignments with Let, Equality Operator

Grasshopper Concepts: print()

1 Like