Northcentral Technical College Introduction To Programming
10-152-310
Introduction to Programming with JavaScript NTC 10-152-310

Learning Plan 4 Nested if Statements

# Nested if Statements

### Nested `if/else` Statements

- What if you want to answer more than one question in a series? Or you want to test a variable for one of many options? We frequently have situations like this in programs. Here's some code snippets that illustrates a common problem
- This is the same as using multiple logical AND (`&&`) expressions. But, with one important difference, we can use `else` statements, too.
- How's this look? A bit complicated? It can get worse...
- But, this kind of coding is not that typical. Over time programmers have figured out that this is very fragile and you never really know if it works right. We now have lots of ways to avoid this type of monster.
- We'll start with some basic patterns of `nesting our logic`.

### Linear Nested `if` Statements

- The linear nested if statement allows us to do many things like testing one variable for many options, and range testing. It uses a new key concept in programming: `else if`.
- Here's how it's used.
- Very frequently, we will also have an `else` statement at the end.

- Here's a larger example. We have a choice variable and the user is asked to make a selection from a list. Doing this with deeply nested if/else statements is ugly! So most languages have better ways. This is usually called the "if, else if, else if, else" pattern among programmers. It looks like this.

- This is a very useful and commonly used structure. The above code replaces what's below and does exactly the same work. Which would you rather do?

### Testing Different Conditions With `if/else` structures.

- Sometimes we just have to nest `if/else` statements as it won't work any other way. We try to limit it and make it concise.

- If we limit the complexity we can manage.

### Range Testing

> We frequently need to test to see if a value is within a range. The technique to solve this combines nested `if/else` with multiple booleans.

- Pick a number between 1 and 10

- Using this technique we can pick from multiple ranges.

### Full Example

- Here's an example that's not in the book: Full Example: Process Customer Record

### And here's the lab

- Anyone who has never made a mistake has never tried anything new. -Albert Einstein

- 4.3 Lab 2
- 4.3 Assignment 2