While joining together several conditions can often help us solve complicated problems, sometimes we need to have conditions within other condition statements. Either or both of the if/else blocks can themselves contain an if statement. This is known as nesting, and can start making the program complicated as you can see by the following flow chart.
To write the above flowchart we would do the following:
When possible, it is easiest to chain together if statements on the else. This is such a common activity that some languages have a special statement, such as Python’s elif, which indicates that there is another condition that should be checked before the else statement. JavaScript simply uses else if, leading to the typical flow of a nested if statement looking like the following:
A game related situation would be the case of the game Rock, Scissors, Paper. Here we have a draw when both players choose the same object, while rock smashes scissors, scissors cuts paper, and paper covers rock. We can chain the possible player 1 choices using else if, and then for each of the choices have a nested if statement for the possible choices of player 2. The amount of necessary work can be further reduced by taking advantage of the simple fact that if both players choose the same object then there is a tie. Below is the code for handling this logic as well as a flowchart showing the logic. On the books git repository is a demo that lets you see the game in action (it uses some material from future chapters but the core conditional logic remains the same).
Nested conditional statements are not the only way of doing this, next section we will learn about another way of joining multiple conditions together in something called a switch.
A quick summary of the basics of JavaScript.
A brief look at how JavaScript was written in 10 days.
Comments. Why programmers don't write them, and how they should be written
Variables are used to store the state of a program.
Bits, Bytes, and data types.
Math on the computer similar but some symbol differences.
Various math operations can be used through the Math class.
Strings are what we call blocks of text and are used extensively.
Determining if a conditional expression is true or false
Conditional code using the if statement.
If statements can contain other if statements, this is called nesting.
Switch statements are a way of replacing large number of else if statements.
Functions let you put common code into a named function that can be called anywhere.
Loops allow you to repeat sections of code until conditions are met.
Just like conditional statements, loops can be nested but this has some special considerations.
Scripting languages give us the ability to dynamically change the web page.
Reacting to the user actions is done by handling events.
Our project for this chapter is a grid search game.
My solution to the Project.