Monday, July 31, 2017

Conditional execution of code

Conditional execution of code
To start, create a simple program that inquires the user to guess a secret number. If they guess correctly, the program says, “Well done!” An interaction at the console might  look like this:
> guess(2)
 undefined
> guess(8)
 Well done!
 undefined
What’s with the ugly appearances of undefined? When you call a function at the console, its code is executed and then its return value is displayed. The guess function in the following listing doesn’t include a return statement so it automatically returns undefined.
var secret = 8;
var guess = function (userNumber) {
 if (userNumber === secret) {
 console.log("Well done!");
 }
};
The guess function checks to see if the user’s number is equal to the secret number. It uses the strict equality operator, ===, and an if statement so that you display the “Well done!” message only if the numbers match. The following sections look at the strict equality operator and the if statement in more detail and introduce the else clause.
12.1.1 The strict equality operator, ===
The strict equality operator compares two values. If they’re equal it returns true; if
they’re not equal it returns false. You can test it at the console:
> 2 === 8
 false
> 8 === 8
 true
> 8 === "8"
 false
> "8" === "8"
 true
Listing 12.1 Guess the number 
http://jsbin.com/feholi/edit?js,console

In the third example, you can see that the strict equality operator doesn’t consider the number 8 and the string "8" to be equal. That’s because numbers and strings are different types of data. The values true and false are a third type of data; they’re called boolean values. In fact, true and false are the only possible boolean values. Boolean values are useful when deciding what a program should do next; for example, by using an if statement.
12.1.2 The if statement
To execute a block of code only when a specified condition is met, you use an if statement
if (condition) {
 // Code to execute
}
If the condition in parentheses evaluates to true, then JavaScript executes the statements in the code block between the curly braces. If the condition evaluates to false, then JavaScript skips the code block. Notice there’s no semicolon after the curly braces at the end of an if statement.
 Listing 12.1 used the strict equality operator to return a true or false value for the condition.
if (userNumber === secret) {
 console.log("Well done!");
}
The code logs the “Well done!” message to the console only if the value of user- Number is equal to the value of secret. For example, say the secret is 8 and the user chooses 2:
if (2 === 8) { // The condition is false.
 console.log("Well done!"); // Not executed
}
If the user chooses 8, the if statement becomes
if (8 === 8) { // The condition is true.
              console.log("Well done!"); // This is executed.
}


Get Programming with JavaScript (2016) John R. Larsen 

No comments:

Post a Comment

Remote Hybrid and Office work