Let's take a look at an if/else statement written in two ways in both Python and JavaScript:
Python | JavaScript |
if a < b: |
let min |
min = a if a < b else b |
let min = (a < b) ? a : b |
In both columns, the code is doing the same thing: a simple test to see whether a is less than b and then assigning the smaller value to the min variable. The first row is a full if/else statement and the second row uses the ternary structure. There are a few grammar rules to note in these examples:
- min must be declared before use, as a best practice. In strict mode, this would actually throw an error.
- Our if clause is encapsulated with parentheses.
- Our if/else statements are encapsulated with curly braces.
- The keywords and operators in the ternary are significantly different (and a bit more cryptic) than in Python.
If we wanted to use what we now know about typeof, we can use strict...