Review
• Nature of Javascript
• How to include Javascript on a page
• Declaring and assigning variables
• Commenting code
Overview
• Operators:allow you to perform mathematical operations in your codecompare values of different variables
• Loops:allow you to control program flow, performing segments of code multiple times
• Conditions:another method of program flow control, allows you to perform segments of code conditionally
Operators• Perform operations on one or more variables or
values in your code.
• Operand: value or variables being operated on by an operator
• Result in a value that can then be assigned or combined with another operator in a more complicated statement.
• For example:var addVar = 1 + 1;var concatString = “Beginning “ + “ and end”;addVar = addVar + 3;
Operator Types
• Mathematical: Perform mathematical calculations
• Assignment: Assign new values to variables, as with the basic assignment operator (=)
• Comparison: Compare two values or variables – evaluates to true or false
• Logical: Used to compare the result of two conditional statements – also evaluates to true or false
Mathematical Operators
• Used for mathematical calculations
• Can be used on any combination of values, variables or evaluated values of other operations
• Some examples:var aNumber = 1 + 1; // evaluates to 2
var anotherNumber = aNumber + 2; // evaluates to 4
var yetAnotherNum = aNumber + anotherNumber;aNumber = 1 + yetAnotherNum * 3; // evaluates to 19
Available Operators• + Addition – Can also be used with string
values
• - Subtraction
• * Multiplication
• / Division – Divides left operand by right operand
e.g. divideResult=10 / 2; // results in 5
• % Modulus – Divides left by right and gives remainder
e.g. modResult=10 % 3; // results in 1
Available Operators, cont.
• The following operators operate on a single variable.
• ++ IncrementAdds 1 to a variableShorthand for: incrVar = incrVar+1;++varName is different to varName++
• -- DecrementSubtracts 1 from a variable
• - NegationNegates the value of a variable
Exercise
• Retrieve mathematic_operators.html from Sakai (https://sakai.bradley.edu/access/content/user/mtovey/)
• Modify lines 24 and 25 to utilize the ++ operator. Use both forms (before and after the variable) to see the difference in operation.
• Modify line 29 to perform a modulo operation instead of division. Note the difference in result.
Assignment operators• Assign a new value to a variable
• For example,assignVar = 1 + 2; // assigns 1 + 2 to assignVar
• Includes the direct assignment operator (=), however the other operators incorporate simple calculations.
Available operators• += Adds the right operand to the left prior to
assigninge.g. addVar += 3; // results in 3 being added to
addVar
Shorthand for: addVar = addVar + 3;
• -= Subtracts right operand from the left before assigning
• *= Multiplies left operand by right before assigning
• /= Divides left operand by right before assigning
• %= Divides left operand by right, then assigns remainder to right operand
Exercise
• Retrieve assignment_operators.html from Sakai
• Modify lines 16 and 22 to experiment with the different assignment operators.
• Modify line 21 to use an assignment operator other than = or +=. Note the resulting outcome in the output text.
Comparison operators
• Compare two values or variables
• Return true or false based on the operator being used and the values being compared.
• For example:compareVar = 3 > 5; // results in false
• Commonly used with loops and conditional statements
Available operators• == Returns true if both operands are
equal
• != Returns true if both operands are not equal
• > Returns true if left operand is greater than right
• >= Returns true if left operand is greater than or equal to right
• < Returns true if left is less than right operand
• <= Returns true if left is less than or equal to right
• === Returns true if both operands are strictly equal
Logical operators
• Used to compare two conditional statements.
• Return true or false based on the operator being used and the results of the two conditional statements.
• Useful for checking multiple conditions at once, simplifying your code.
Available operators
• && (AND) Returns true if both conditionals are true
e.g. andVar = 1 < 3 && 2 > 0;
• || (OR) Returns true if one conditional is true
e.g. orVar = 1 < 3 || 2 > 5;
• ! (NOT) Returns true if the conditional evaluates to false
e.g. notVar = !(3 < 1);
Combining operators
• Multiple operators can be combined into one statement, streamlining your codee.g. combVar = 1 + 2 * 8 / 3;
• Order of operation rules needs to considered in these cases to ensure your statements evaluate how you intend.
• Parentheses override order of operation and aid in readability.e.g. combVar = (1 + 2) * (8 / 3);
Exercise
• Retrieve final_operators.html from Sakai
• Modify the values and comparison operators in the first script block to experiment with the different comparison operators.
• Add a fourth variable declaration to the third script block and assign it a numeric value. Modify the statements on lines 67 and 72 to include this new variable and another mathematical operator. Experiment with different operators and parentheses to gain a better understanding of order of operation.
Conditionals and Loops
• Conditionals and loops allow greater control over program flow, beyond simple sequential execution of statements
• Combined with statements constructed with logical and comparison operators, conditionals allow you to execute segments of code only when certain conditions are met
• Loops allow you to execute segments of code repeatedly.
Defining conditionals
• Conditionals consist of the condition to be checked against, the code to be executed if it evaluates to true and, optionally, code to be executed if false.
• if (condition) {…statements to be executed…
} else {…statements to be executed…
}
Using conditionals
• Useful, for example, to display output depending on the value of a variable.
• For example:var inputAge=25;if(inputAge <= 9) {
alert(“You were born in the 2000’s”);} else {
alert(“You are older than 10”);}
Combining conditionals
• Conditionals can be nested in order to create more complicated scenarios. Nesting means to put a code structure inside a structure of a similar nature.
• For example: if(inputAge <= 9) {
if(gender == “male”) {alert(“You are a young boy”);
} else {alert(“You are a young girl”);
}} else {
alert(“You are older than 10”);}
Conditionals, cont.
• Else if allows you to add branches to an if / else conditional:if (aNumber < 10) {
alert(‘The number is less than 10’);} else if(aNumber < 20) {
alert(‘The number is between 10 and 20.’);} else {
alert(‘The number is 20 or above’);}
• Switch allows you to perform different actions based on the value of a single variable or the value of an expression.
• Can be used as shorthand for an if / else if / else construct that examines one variable.
Conditionals, cont.
• myCountry = “United States”;switch (myCountry) {
case(“France”):alert(“You live in Europe”);break;
case(“China”):alert(“You live in Europe”);break;
case(“United States”):alert(“You live in North America”);break;
default:alert(“I’m not sure where you live”);
}
Exercise
• Retrieve conditionals.html from Sakai
• Modify the if statement in the code to check for a value of Chicago and output a different message if detected.
• Further modify the if statement to output another different message if neither Peoria or Chicago is detected as the input value.
Defining Loops• Loops take two forms: the for loop and the while loop.
• The for loop executes a segment of code a certain number of times:for (intializer;stop condition;control) {
…code to be executed…}
• The while loop executes a segment of code while a conditional statement evaluates to true:while (condition) {
…code to be executed…}
Using Loops
• Loops aid with streamlining your code, allowing a single set of instructions to be executed multiple times without having to be typed out repeatedly.
• for (var count=0;count < 10;count++) {document.write(‘Looping, count is: ‘ + count);
}
• var inString=“”;while(inString!=“quit”) {
alert(“Entered string is currently: “ + inString);
inString=prompt(“Please enter a new value”);}
Loops, cont.
• Alternative form of while:do {
…code to be executed…} while (condition)
forces code block to be executed at least once
• Loops can also be nested
• break and continue allow you to explicitly stop processing of a loop prior to the end of the block
Exercise
• Retrieve loops.html from Sakai
• Modify the structure of the for loop and the values of the count variable to experiment with how the for loop functions.
• Modify the for loop so that it counts to 20 in increments of 2.
• Currently the while loop will not show any output if ‘quit’ is entered as the first value. Modify the while loop so that the first entered value is always shown.