The Ternary Operator
Learn how to use the ternary operator to improve our code flow.
We'll cover the following...
The if/else
statement
Let’s see how this statement works:
We all have choices to make. This is why all programming languages offer some variation of the if/else statement
.
Press + to interact
function choices(thirsty) {if (thirsty) {return 'beer';} else {return 'hamburger';}}console.log(choices(true));
The code snippet above prints beer
when thirsty
is true
and hamburger
when thirsty
is false
.
Note: Some languages are very strict about their booleans. For example, Java and C# would require a boolean for
thirsty
and reject anything else. Other languages, like Python and JavaScript, are true to their dynamic nature. They are more flexible and only require the values to be. This means they will ... truthy In JavaScript, a value is truthy if JavaScript’s built-in type coercion converts it to true.