Javascript Ternary Operator Assignment 2

Sometimes we need to perform different actions based on a condition.

There is the statement for that and also the conditional (ternary) operator for conditional evaluation which we will be referring as the “question mark” operator for simplicity.

The “if” statement

The statement gets a condition, evaluates it and, if the result is , executes the code.

For example:

In the example above, the condition is a simple equality check: , but it can be much more complex.

If there is more than one statement to be executed, we have to wrap our code block inside curly braces:

It is recommended to wrap your code block with curly braces every time with , even if there is only one statement. That improves readability.

Boolean conversion

The statement evaluates the expression in parentheses and converts it to the boolean type.

Let’s recall the conversion rules from the chapter Type Conversions:

  • A number , an empty string , , and become . Because of that they are called “falsy” values.
  • Other values become , so they are called “truthy”.

So, the code under this condition would never execute:

…And inside this condition – always works:

We can also pass a pre-evaluated boolean value to , like here:

The “else” clause

The statement may contain an optional “else” block. It executes when the condition is wrong.

For example:

Several conditions: “else if”

Sometimes we’d like to test several variants of a condition. There is an clause for that.

For example:

In the code above JavaScript first checks . If it is falsy it then goes to the next condition , and otherwise shows the last .

There can be more blocks. The ending is optional.

Ternary operator ‘?’

Sometimes we need to assign a variable depending on a condition.

For instance:

The so-called “ternary” or “question mark” operator lets us do that shorter and simpler.

The operator is represented by a question mark . The formal term “ternary” means that the operator has three operands. It is actually the one and only operator in JavaScript which has that many.

The syntax is:

The is evaluated, if it’s truthy then is returned, otherwise – .

For example:

Technically, we can omit parentheses around . The question mark operator has a low precedence. It executes after the comparison , so that’ll do the same:

But parentheses make the code more readable, so it’s recommended to use them.

Multiple ‘?’

A sequence of question mark operators allows returning a value that depends on more than one condition.

For instance:

It may be difficult at first to grasp what’s going on. But after a closer look we can see that it’s just an ordinary sequence of tests.

  1. The first question mark checks whether .
  2. If true – returns , otherwise – goes after the colon and checks for .
  3. If that’s true – returns , otherwise – goes after the next colon and checks for .
  4. If that’s true – returns , otherwise – goes after the last colon and returns .

The same logic using :

Non-traditional use of ‘?’

Sometimes the question mark is used as a replacement for :

Depending on the condition , either the first or the second part after gets executed and shows the alert.

We don’t assign a result to a variable here. The idea is to execute different code depending on the condition.

It is not recommended to use the question mark operator in this way.

The notation seems to be shorter than , which appeals to some programmers. But it is less readable.

Here is the same code with for comparison:

Our eyes scan the code vertically. The constructs which span several lines are easier to understand than a long horizontal instruction set.

The idea of a question mark is to return one or another value depending on the condition. Please use it for exactly that. There is to execute different branches of the code.

In the example above it’s possible to evade the question mark operator, because the comparison by itself returns :

Introduction

In programming, there will be many occasions in which you will want different blocks of code to run depending on user input or other factors.

As an example, you might want a form to submit if each field is filled out properly, but you might want to prevent that form from submitting if some required fields are missing. In order to achieve tasks like these we have conditional statements, which are an integral part of all programming languages.

Conditional statements execute a specific action based on the results of an outcome of or .

A few examples of JavaScript conditional statements you might see include:

  • Check the location of a user and display the correct language based on country
  • Send a form on submit, or display warnings next to missing required fields
  • Open a dropdown on a click event, or close a dropdown if it is already open
  • Display an alcohol purveyor's website if the user is over the legal drinking age
  • Display the booking form for a hotel but not if the hotel is booked

Conditional statements are part of the logic, decision making, or flow control of a computer program. You can compare a conditional statement to a "Choose Your Own Adventure" book, or a flowchart.

In this tutorial, we will go over conditional statements, including the , , and keywords. We will also cover the ternary operator.

If Statement

The most fundamental of the conditional statements is the statement. An statement will evaluate whether a statement is true or false, and only run if the statement returns . The code block will be ignored in the case of a result, and the program will skip to the next section.

An statement is written with the keyword, followed by a condition in parentheses, with the code to be executed in between curly brackets. In short, it can be written as .

Here is a longer examination of the basic statement.

The contents of an statement are indented, and the curly brackets containing the block of code to run do not end in a semicolon, just like a function block.

As an example, let's consider a shopping app. Say, for the functionality of this app, a user who has deposited a certain amount of funds into their account would then like to buy an item from the store.

shop.js

We have an account balance of , and want to buy a pair of jeans for . Using the less than or equal to operator, we can check if the price of jeans is less than or equal to the amount of funds we have. Since evaluates to , the condition will pass and the block of code will run.

In a new example, we will create a new shop item that costs more than the available balance.

shop.js

This example will have no output, since evaluates to . The code block will simply be ignored, and the program will proceed to the next line.

Else Statement

With statements, we only execute code when a statement evaluates to , but often we will want something else to happen if the condition fails.

For example, we might want to display a message telling the user which fields were filled out correctly if a form did not submit properly. In this case, we would utilize the statement, which is the code that will execute if the original condition does not succeed.

The statement is written after the statement, and it has no condition in parentheses. Here is the syntax for a basic statement.

Using the same example as above, we can add a message to display if the funds in the account are too low.

shop.js

Since the condition did not succeed, the code moves on to what's in the statement.

This can be very useful for showing warnings, or letting the user know what actions to take to move forward. Usually an action will be required on both success and failure, so is more common than a solo statement.

Else if Statement

With and , we can run blocks of code depending on whether a condition is or . However, sometimes we might have multiple possible conditions and outputs, and need more than simply two options. One way to do this is with the statement, which can evaluate more than two possible outcomes.

Here is a basic example of a block of code that contains an statement, multiple statements, and an statement in case none of the conditions evaluated to .

JavaScript will attempt to run all the statements in order, and if none of them are successful, it will default to the block.

You can have as many statements as necessary. In the case of many statements, the statement might be preferred for readability.

As an example of multiple statements, we can create a grading app that will output a letter grade based on a score out of 100.

The requirements of this app are as follows:

  • Grade of 90 and above is an A
  • Grade of 80 to 89 is a B
  • Grade of 70 to 79 is a C
  • Grade of 60 to 69 is a D
  • Grade of 59 or below is an F

Below we will create a simple set of , , and statements, and test them against a given grade.

grades.js

In our example, we first check for the highest score, which will be greater than or equal to . After that, the statements will check for greater than , , and until it reaches the default of a failing grade.

Although our value of is technically also true for , and , the statements will stop at the first one that is successful. Therefore, we get an output of , which is the first match.

Ternary Operator

The ternary operator, also known as the conditional operator, is used as shorthand for an statement.

A ternary operator is written with the syntax of a question mark () followed by a colon (), as demonstrated below.

In the above statement, the condition is written first, followed by a . The first expression will execute on , and the second expression will execute on . It is very similar to an statement, with more compact syntax.

In this example, we will create a program that checks if a user is or older. If they are, it will print to the console. If they are not, it will print to the console.

age.js

Since the of the user was less than , the fail message was output to the console. The equivalent to this would be in the statement, and in the statement.

Conclusion

Conditional statements provide us with flow control to determine the output of our programs. They are one of the foundational building blocks of programming, and can be found in virtually all programming languages.

In this article, we learned about how to use the , , and keywords, and covered nesting of statements, and use of the ternary operator.

One thought on “Javascript Ternary Operator Assignment 2

Leave a Reply

Your email address will not be published. Required fields are marked *