Introduction to Conditional Statements
Introduction to Conditional Statements
Introduction to Conditions
Introduction to Boolean Values
Both C# and JavaScrit share the same ancestry of C-based or C-oriented languages. One of the concepts that both languages share is that of conditional statements. They just have some slight differences on a couple of operators.
The JavaScript language supports Boolean variables and values the same way as C#.
A Boolean Variable
To start a Boolean value, declare a variable using the var keyword. If you want to indicate that it is Boolean, initialize it with the true or the false value. Here is an example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script>
function checkStatus() {
var sleeping = true;
}
</script>
</body>
</html>
In the same way, if the variable had already been declared, at any time, you can assign a Boolean value to it. As seen with C#, you can also assign a Boolean expression to the variable.
When creating a function, you can add a parameter to it and treat it as a Boolean value. When creating a form, you can use webcontrols such as the check box, the radio button, the combo box, etc to handle Boolean values.
Introduction to Conditions
As seen in C#, the most fundament way to formulate a conditional statement is with the if keyword. JavaScript follows the same formula as C#:
if(condition) { statement; }
The description is the same we saw for the statement in C#. Microsoft Visual Studio can also assist you in crreating a conditional statement. To do this, right-click the section of the Code Editor where you want to create it and click Insert Snippet...
Boolean Operators
Equality
To let you compare two values or objects for equality, JavaScript provides the === operator. It is used as in value1 === value2. If value1 and value2 are equal, the condition is true. Otherwise the condition is false. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Compound Interest</title> </head> <body> <h1>Compound Interest</h1> <form name="CompoundInterest" method="post"> <table> <tr> <td><label for="periods" style="font-weight: 600;">Periods:</label></td> <td><input type="number" class="periods" style="width: 80px" /> <select class="frequency"> <option>Years</option> <option>Months</option> <option>Days</option> </select></td> </tr> <tr> <td> </td> <td><input type="button" value="Calculate" class="calculate" style="width: 80px" /></td> </tr> </table> </form> <script> var selected = document.querySelector('select'); var btnCalc = document.querySelector('.calculate'); btnCalc.addEventListener('click', function () { if (selected.value === 'Months') { } }); </script> </body> </html>
Non-Equality
To let you find out if one value is different from another, JavaScript provides the !== operator. It is used as in value1 !== value2. If value1 and value2 are different, the condition is true.
A Lower Value
To find out if one value is lower than another, use the < operator as in value1 < value2. To find out if a value is equal or lower than another, use the <= operator.
A Higher Value
To find out if a value is greater than another, use the > operator as in value1 > value2. Here is an example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Traffic Ticket System</title>
</head>
<body>
<h1 style="font-size: 14px;">Traffic Ticket System</h1>
<p class="message">Find out why the police officer stopped you.</p>
<script>
'use strict';
var speedLimit = 30;
var drivingSpeed = 62;
var excuseSpeed = speedLimit + 10;
var msg = document.querySelector('.message');
function composeMessage() {
if (drivingSpeed > excuseSpeed) {
msg.textContent = 'Hello, I stopped you because you were doing ' + drivingSpeed + ' on a ' + speedLimit + 'MPH street.';
}
}
msg.addEventListener('click', composeMessage);
</script>
</body>
</html>
To know whether if a value is equal or higher than another, use the >= operator.
Primary Options with Boolean Statements
Initializing or Updating a Boolean Variable
You can assign a Boolean expression to a variable. An example would be isFullTime = jobTitle == "Contractor". Remember that, to make your code easier to read, you should put the Boolean expression in parentheses. Here is an example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script>
function checkStatus() {
var isFullTime = true;
var jobTitle = "Manager;"
// . . .
isFullTime = (jobTitle == "Contractor");
}
</script>
</body>
</html>
Creating Multiple Statements
In your code, if you want to perform many comparisons, you can create as many statements, each using its own condition. Here are examples:
<script> var interest = 0.00; var princ = document.querySelector('.principal'); var iRate = document.querySelector('.interestRate'); var per = document.querySelector('.periods'); var selected = document.querySelector('select'); var btnCalc = document.querySelector('.calculate'); var para = document.querySelector('p'); btnCalc.addEventListener('click', function () { if (selected.value == 'Years') { interest = princ.value * iRate.value * per.value / 100.00; } if (selected.value == 'Months') { interest = princ.value * (iRate.value / 100.00) * (per.value / 12); } if (selected.value == 'Days') { interest = princ.value * (iRate.value / 100.00) * (per.value / 360); } }); </script>
The Logical NOT Operator
Like C#, JavaScript supports the idea of negating a a condition by preceding it with the ! operator. As a reminde, the formula to follow is:
!variable-or-expression
Here is an example we saw with C#:
<script>
var employed = true;
var validation = !employed;
</script>
if There Are Alternatives
What else Condition?
Like C#, JavaScript supports the else keyword that can accompany an if condition to check for an alternate outcome. As a reminder, tormula to follow is:
if(condition) { statement(s)1; } else { statement(s)2; }
Each condition can have as many statements as you want.
The Ternary Operator (?:)
Like C#, JavaScript supports the ternary operator as an alternate to an if...else. As a Reminder, the formula to follow is:
condition ? statement1 : statement2;
if...else if
Consider a combination of if...else conditions as follows:
<script>
var princ = document.querySelector('.principal');
var iRate = document.querySelector('.interestRate');
var per = document.querySelector('.periods');
var selected = document.querySelector('select');
var btnCalc = document.querySelector('.calculate');
btnCalc.addEventListener('click', function () {
if (selected.value == 'Years') {
interest = princ.value * iRate.value * per.value / 100.00;
}
else {
interest = princ.value * (iRate.value / 100.00) * (per.value / 12);
}
});
</script>
Sometimes an else condition may lead to more than one outcome. In such a case, you can add an if condition after else. As a reminder, the formula to follow is:
if(condition1) { statement(s)1; } else if(condition2) { statement(s)2; }
if...else if...else
As done in C#, you can add an else condition that embraces the other outcome(s). As a reminder, the formula to follow is:
if(condition1){ statement(s)1; } else if(condition2) { statement(s)2; } else { statement(s)_n; }
if...else if...else if...else
After the first if condition, you can create as many else if conditions as you want. As seen in C#, the formula to follow is:
if(condition1) { statement(s)1; } else if(condition2) { statement(s)2; } . . . else if(condition_n) { statement(s)_n; } else { statement(s)-n; }
Logical Conjunctions and Disjunctions
Nesting a Conditional Statement
As done in C#, you can nest one or more conditions in a conditional statement of your JavaScript code. This is referred to as nesting. Things are done exactly the same as in C#. As a reminder, the formula to nest one condition in another is:
if( condition1 ) { if( condition2 ) { statement(s) } }
You can also use a ternary operator to nest a condition in another. You can also nest a condition in a condition that itself is nested.
Boolean Conjunctions
A Boolean conjunction is the ability to join two condition so that both must be true. JavaScript supports conjunction in the exact same way C# does. This is done using the && operator. As a reminder, the operator is used in a formula as follows:
condition1 && condition2
In the same way, you can combine conjunctions as follows:
condition1 && condition2 && condition3 && . . . && condition_n
The conjunction is usually created in an if conditional statement or it's variants that involve the else alternatives.
Boolean Disjunctions
JavaScript supports the ability to join two or more conditions so that only one of them needs to be true for the whole group of conditions to be true. Such as group is referred to as a disjunction. As seen in C#, JavaScript supports disjunctions through the || operator. The formula to disjoin two conditions is:
condition1 || condition2
Here is an example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Traffic Ticket System</title>
</head>
<body>
<h1 style="font-size: 14px;">Traffic Ticket System</h1>
<p class="message">Traffic Camera</p>
<script>
'use strict';
var vehicleType = 'ambulance';
var msg = document.querySelector('.message');
function composeMessage() {
if (vehicleType == 'police' || vehicleType == 'ambulance') {
msg.textContent = "This is a service vehicle. Don't issue speed ticket.";
}
}
msg.addEventListener('click', composeMessage);
</script>
</body>
</html>
You can also set the value of a Boolean variable with a conjunction. Here is an example:
var canBeExcused = vehicleType == 'police' || vehicleType == 'ambulance';
Such a variable can be compared with true or false to get its current value. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Traffic Ticket System</title> </head> <body> <h1 style="font-size: 14px;">Traffic Ticket System</h1> <p class="message">Traffic Camera</p> <script> 'use strict'; var vehicleType = 'personal'; var canBeExcused = vehicleType == 'police' || vehicleType == 'ambulance'; var msg = document.querySelector('.message'); function composeMessage() { if (canBeExcused == true) { msg.textContent = "This is a service vehicle. Don't issue speed ticket."; } } msg.addEventListener('click', composeMessage); </script> </body> </html>
In this case, you can just use the nameo the variable in the comparison. Here is an example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Traffic Ticket System</title> </head> <body> <h1 style="font-size: 14px;">Traffic Ticket System</h1> <p class="message">Traffic Camera</p> <script> 'use strict'; var vehicleType = 'police'; var canBeExcused = ((vehicleType == 'police') || (vehicleType == 'ambulance')); var msg = document.querySelector('.message'); function composeMessage() { if (canBeExcused) { msg.textContent = "This is a service vehicle. Don't issue speed ticket."; } } msg.addEventListener('click', composeMessage); </script> </body> </html>
You can also disjoin more than two conditions using the following formula:
condition1 || condition2 || . . . || condition_n
Here an example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Traffic Ticket System</title>
</head>
<body>
<h1 style="font-size: 14px;">Traffic Ticket System</h1>
<p class="message">Traffic Camera</p>
<script>
'use strict';
var vehicleType = 'government';
var isServiceVehicle = false;
var canBeExcused = ((vehicleType == 'law enforcement') ||
(vehicleType == 'ambulance') ||
(vehicleType == 'government'));
var msg = document.querySelector('.message');
function composeMessage() {
if (canBeExcused) {
msg.textContent = "This is a service vehicle. Don't issue speed ticket.";
}
}
msg.addEventListener('click', composeMessage);
</script>
</body>
</html>
Switching Conditions
Introduction
Once again, as a member of the C-based languages, JavaScript support the idea of using a value and considering the possible matches of that value. This is done by using a combination of the switch and the case keywords. As seen in C#, the primary formula to follow is:
switch(expression) { case choice1: statement1; break; case choice2; statement2; break; case choice-n; statement-n; break; }
Each case considers one possible value of the expression.
A default Case
If you think there is a possible value thet doesn't match any of the choices, you should add an outcome that uses the default keyword. This leads to a formula as follows:
switch(expression) { case choice1: statement1; break; case choice2: statement2; break; case choice-n: statement-n; break; default: default-statement; break; }
Everything follows the description we reviewed for the switch condition in C#, excluding the pattern matching.
Introduction to Built-In Classes/Objects and Boolean Functions/Methods
To support Boolean values, the JavaScript language provides a class named Boolean. You can use it to initialize a Boolean variable or set its value. Here is an example:
<script> var playing = new Boolean(true); </script>
You can then use the variable like any Boolean variable. Still, there is no particular reason to use that class to initialize a Boolean variable. The var keyword knows what to do with a variable initiatize with a true value, a false value, or a Boolean expression.
Numbers
Introduction
To support the numbers used on a webpage, JavaScript provides a class named Number. One of the major concerns with numbers is how they interact with the other values in code. In fact, the usual primary operation is to convert a value to a number.
This is Not a Number
To start, the Number class is equipped with a field named NaN. This constant is used to determine that a value is not a number, or whenever the JavaScript interpreter is not able to conclude that something is a number, it decides that the thing is not a number.
To accompany the NaN constant, the Number class is equipped with a Boolean method named isNaN. Its syntax is:
bool isNaN(value);
This method takes one argument, which is a value to analyze. If the argument is a valid number, this method returns true (this method analyzes a value to formulate a conclusion; it doesn't produce the number). If the argument doesn't hold a valid number, this method returns false; in this case, this also means that the argument is NaN. Here is an example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Traffic Ticket System</title>
</head>
<body>
<h1 style="font-size: 14px;">Traffic Ticket System</h1>
<form name="TrafficSystem" method="post">
<table>
<tr>
<td><label for="speedLimit">Speed Limit:</label></td>
<td><input type="text" id="speedLimit" class="speedLimit" value="30" /></td>
</tr>
<tr>
<td><label for="drivingSpeed">Driving Speed:</label></td>
<td><input type="text" id="drivingSpeed" class="drivingSpeed" placeholder="Enter the speed of the vehicle" /></td>
</tr>
<tr>
<td> </td>
<td><input type="button" class="calculate" value="Calculate Difference" /></td>
</tr>
<tr>
<td><label for="speedDifference">Speed Difference:</label></td>
<td><input type="text" id="speedDifference" class="speedDifference" /></td>
</tr>
</table>
</form>
<script>
'use strict';
var speedLimit = document.querySelector('.speedLimit');
var drivingSpeed = document.querySelector('.drivingSpeed');
var speedDifference = document.querySelector('.speedDifference');
var btnCalculate = document.querySelector('.calculate');
function showNumber() {
if (isNaN(drivingSpeed.value) == true) {
speedDifference.value = 0;
}
else {
speedDifference.value = drivingSpeed.value - speedLimit.value;
}
}
btnCalculate.addEventListener('click', showNumber);
</script>
</body>
</html>
By the way, most of the time, you don't have to compare a Boolean function call to true as in == true or === true. The tuthfulness is implied.
Converting a Value to a Number
Both the the Number class and JavaScript provides various means to convert a value to a number, or to attempt to do so. To assist you, the Number class is equiipped with a constructor that takes one argument. Its syntax is:
new Number(value);
Actually, this constructor can be used, and is mostly used, as a method. In this case, we can say that the Number class is equiipped with a method named Number whose syntax is:
number Number(value);
This method (and its constructor) takes one argument as the value to be converted. If the argument holds a valid value, this method produces that number. If the argument holds something that is not a number, or the JavaScript interpreter cannot conclude that the number is valid, the method returns the NaN constant. Consider the following example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Compound Interest</title>
</head>
<body>
<h1>Compound Interest</h1>
<form name="CompoundInterest" method="post">
<table>
<tr>
<td><label for="principal" style="font-weight: 600;">Principal:</label></td>
<td><input type="number"
class="principal" style="width: 80px" /></td>
</tr>
<tr>
<td><label for="interestRate" style="font-weight: 600;">Interest Rate:</label></td>
<td><input type="number" class="interestRate"
style="width: 60px" />%</td>
</tr>
<tr>
<td><label for="periods" style="font-weight: 600;">Periods:</label></td>
<td><input type="number" class="periods" style="width: 80px" />
<select class="frequency">
<option>Years</option>
<option>Months</option>
<option>Days</option>
</select></td>
</tr>
<tr>
<td> </td>
<td><input type="button" value="Calculate"
class="calculate" style="width: 80px" /></td>
</tr>
<tr>
<td><label for="interestAmount" style="font-weight: 600;">Interest Amount:</label></td>
<td><input type="number" class="interestAmount"
style="width: 80px" />
</td>
</tr>
<tr>
<td><label for="futureValue" style="font-weight: 600;">Future Value:</label></td>
<td><input type="number" class="futureValue"
style="width: 80px" />
</td>
</tr>
</table>
</form>
<script>
var princ = document.querySelector('.principal');
var iRate = document.querySelector('.interestRate');
var per = document.querySelector('.periods');
var iAmount = document.querySelector('.interestAmount');
var future = document.querySelector('.futureValue');
var frequency = document.querySelector('.frequency');
var selected = document.querySelector('select');
var btnCalc = document.querySelector('.calculate');
var para = document.querySelector('p');
btnCalc.addEventListener('click', function () {
if (selected.value == 'Years') {
interest = princ.value * iRate.value * per.value / 100.00;
}
if (selected.value == 'Months') {
interest = princ.value * (iRate.value / 100.00) * (per.value / 12);
}
if (selected.value == 'Days') {
interest = princ.value * (iRate.value / 100.00) * (per.value / 360);
}
var total = Number(princ.value) + interest;
future.value = total;
iAmount.value = interest;
});
</script>
</body>
</html>
|
||
Previous | Copyright © 2004-2019, FunctionX | Next |
|