Controllo del flusso
When your program contains more than one statement, the statements are executed, predictably, from top to bottom. As a basic example, this program has two statements. The first one asks the user for a number, and the second, which is executed afterward, shows the square of that number.
var theNumber = Number(prompt("Pick a number", "")); alert("Your number is the square root of " + theNumber * theNumber);
Nota: viene eseguita solo nel browser, ho costruito il collage 😊
Number converts a value to a number. We need that conversion because the result of prompt is a string value, and we want a number. There are similar functions called
Boolean that convert values to those types.
Here is the rather trivial schematic representation of straight control flow:
Executing statements in straight-line order isn’t the only option we have. An alternative is conditional execution, where we choose between two different routes based on a Boolean value, like this:
Conditional execution is written with the
var theNumber = Number(prompt("Pick a number", "")); if (!isNaN(theNumber)) alert("Your number is the square root of " + theNumber * theNumber);
With this modification, if you enter “cheese” [o “otto” o qualunque cosa che non sia un numero], no output will be shown.
if executes or skips a statement depending on the value of a Boolean expression. The deciding expression is written after the keyword, between parentheses, followed by the statement to execute.
true only if the argument it is given is
Number function happens to return
NaN when you give it a string that doesn’t represent a valid number. Thus, the condition translates to “unless
theNumber is not-a-number, do this”.
You often won’t just have code that executes when a condition holds
true, but also code that handles the other case. This alternate path is represented by the second arrow in the diagram. The else keyword can be used, together with
if, to create two separate, alternative execution paths.
var theNumber = Number(prompt("Pick a number", "")); if (!isNaN(theNumber)) alert("Your number is the square root of " + theNumber * theNumber); else alert("Hey. Why didn't you give me a number?");
If we have more than two paths to choose from, multiple
if/else pairs can be “chained” together. Here’s an example:
var num = Number(prompt("Pick a number", "0")); if (num < 10) alert("Small"); else if (num < 100) alert("Medium"); else alert("Large");
The program will first check whether num is less than 10. If it is, it chooses that branch, shows “Small”, and is done. If it isn’t, it takes the else branch, which itself contains a second if. If the second condition (< 100) holds, that means the number is between 10 and 100, and “Medium” is shown. If it doesn’t, the second, and last,
else branch is chosen.
The flow chart for this program looks something like this: