wdmd 170 – uw stevens point 1 wdmd 170 internet languages elesson: data types and operators (non...
TRANSCRIPT
1WDMD 170 – UW Stevens Point
WDMD 170 Internet Languages
eLesson: Data Types and Operators
(NON Audio Version)
© Dr. David C. Gibbs2003-04
2WDMD 170 – UW Stevens Point
Tutorial 3
Data Types and Operators
Section B - Expressions and Operators
3WDMD 170 – UW Stevens Point
Tutorial 3B Topics
• Section B - Expressions and Operators– Understand the components of an expression– How to use expressions– How to use arithmetic, assignment,
comparison, and logical operators– How to work with strings– How to create the calculator program– Understand how “mixed expressions” are
evaluated in JavaScript
4WDMD 170 – UW Stevens Point
Expressions in JavaScript
• Expressions1.A literal value – string, integer, floating
point, Boolean, or null2.A variable – string, integer, floating
point, Boolean3.A combination of literal values,
variables – where the values are combined to form longer expressions
5WDMD 170 – UW Stevens Point
Expressions – three types• Expressions
1. A literal value – string, integer, floating point, Boolean, or null• “this string literal is an expression”• 15 // is an integer expression• 3.14 // is a floating point expression
2. A variable – string, integer, floating point, Boolean• var mySchool = “UWSP”;
// mySchool can be considered an expression• var myScore = 87;
// myScore can be considered an expression3. A combination of literal values, variables – where the values
and variables are combined using operators• mySchool + “ is a very fine school!”
// a concatenated string expression• myScore + 15
// an arithmetic expression [NOTE: “+” is a versatile operator! It “adds” numbers and strings!]
6WDMD 170 – UW Stevens Point
Operators and Operands
• Operators and operands can be used to create more complex expressions– Operands
• Variables and literals contained in an expression
– Operators• Symbols used in expressions to manipulate
operands
– Examples• myScore + 15 // arithmetic operator +• myNumber = 100; // assignment operator =
8WDMD 170 – UW Stevens Point
JS Operators by Type
Arithmetic +, =, *, /, %
Assignment =, +=, -=, *=, /=, %=
Comparison ==, !=, >, <, >=, <=, ===, !==
Logical !, &&, ||
String +, +=
9WDMD 170 – UW Stevens Point
Binary vs. Unary Operators• Can be binary or unary
– Binary• Requires an operand both before (left operand) and after
(right operand) the operator myNumber = 100 (assignment)
myVar1 + myVar2 (arithmetic addition)
– Unary• Requires a single operand either before or after the
operatormyNumber++ (arithmetic – post-
increment) -3 (arithmetic – prefix
negation)
10WDMD 170 – UW Stevens Point
Arithmetic Operators• Used to perform mathematical calculations• Comprised of both binary and unary operators• NOTE: the “addition” operator (+)
• when used between numeric literals or variables results in a “sum”
5 + 2 results in 7• when used between string literals or variables concatenates
the operands“hi” + “ there” yields “hi there”
• when used as a unary prefix operator, denotes “positive” value (as in “positive 5”)
+5 • what do you suppose happens when + is used between
operands of differing types?e.g. 5 + “two”(more on this later in this eLesson!)
12WDMD 170 – UW Stevens Point
The “modulus” operator: %
• Modulus is a fancy name for “remainder”.
• Recall (from elementary school) that 11/4 is 2 with 3 “left over”.
• In JS, 11/4 gives 2.75, but 11%4 gives 3 // copy this between script tags to prove it!document.writeln("11 / 4 is: " + 11/4 );document.writeln("11 % 4 is: " + 11%4 );
• So % is an operator designed to give the “remainder” from two numeric operands.
13WDMD 170 – UW Stevens Point
• Refer to the instructions on pages 141-2 (Gosselin).• Create the file ArithmeticExamples.htm and save it in
your Tutorial03 folder.• Add these lines after the multiplication statement to
illustrate modulus:result = number % 6;
document.writeln("Result after modulus = " + result);
• Preview the .htm file (here are the results I obtained):Result after addition = 150
Result after division = 25
Result after subtraction = 75
Result after multiplication = 200
Result after modulus = 4
Result after increment = 101
• After the calculations, add an explanation in your HTML document indicating why number % 6 is 4.
eTask 1
14WDMD 170 – UW Stevens Point
Unary Arithmetic OperatorsUnary operators: +, -, ++, and --• + 3 and -5 have already been discussed as prefix
unary operators that establish the “sign” of a value
• Prefix operators ++ or --– Placed before the operand
• ++count or --count– Increments or decrements the variable; the value is
returned after the operation occurs – hence “prefix” or “pre-increment”
• Postfix operators ++ or --– Placed after the operand
• count++ or count--– the value is returned before operation; then the variable
is incremented or decremented – hence “postfix” or “post-increment”
15WDMD 170 – UW Stevens Point
Operator ++• Clarification
– count++ and ++count both add 1 to the previous contents of count– that is, both are equivalent to count = count + 1;
• Example 1– however, the prefix operator executes before returning the value
var count = 1;
document.writeln(++count); // displays 2, count contains 2• Example 2
– The postfix operator returns the current value and then executes the operation
var count = 1;
document.writeln(count++); // displays 1, count contains 2
16WDMD 170 – UW Stevens Point
Operator ++The code of Example 1
var count = 1;
document.writeln(++count);
is equivalent to these statements:var count = 1;
count = count + 1;
document.writeln(count)
The output is: 2The value in count is: 2
The code of Example 2var count = 1;
document.writeln(count++);
is equivalent to these statements:var count = 1;
document.writeln(count)
count = count + 1;
The output is: 1The value in count is: 2
17WDMD 170 – UW Stevens Point
1. Copy and paste the following code sample into a new HTML document in HTML-Kit. Save the file as IncrementDecrementOperators.htm in your Tutorial03 folder. Preview your results.
<pre><script>
var count = 3;
document.writeln("count is: " + count);
document.writeln("++count is: " + ++count);
document.writeln("count is: " + count);
document.writeln();
var count = 3;
document.writeln("count is: " + count);
document.writeln("count++ is: " + count++);
document.writeln("count is: " + count);
document.writeln();
</script></pre>
2. Below the </pre> tag in your document (so your explanation appears in the document), explain how and why the results differ.
eTask 2
18WDMD 170 – UW Stevens Point
Assignment Operators =, +=• Used for assigning a value to a variable• Basic assignment operator (=)
– Assign initial value to new variablevar discountRate = 0.10;
– Assign a new value to an existing variablediscountRate = 0.15;
– Assign the result of an expressiontemperatureCels = 5/9*(temperatureFahr-32);
• Arithmetic assignment operator– Provides a shorthand notation for common statements
sum = sum + 5; // is functionally the same as sum += 5; // an abbreviated form
20WDMD 170 – UW Stevens Point
Arithmetic Assignment Operators -=, *=, /=
netPay = netPay - FICA; // is functionally the same as netPay -= FICA; // an abbreviated form
investmentEarnings = investmentEarnings * 2;
investmentEarnings *= 2; // double your money
salary = salary / 2;
salary /= 2; // cut in half
22WDMD 170 – UW Stevens Point
Refer to the instructions on pages 145-6 (Gosselin).
• Create the file AssignmentExamples.htm and save it in your Tutorial03 folder.
• Preview the .htm file.
eTask 3
23WDMD 170 – UW Stevens Point
NOTE: Arithmetic Assignment Operators can cause problems!
var x = "one hundred";var y = 5;x *= y;document.writeln(x); //result is “NaN” – see Gosselin page 144
What is NaN?– Not a Number– returned when a mathematical expression
does not result in a numerical value– here you cannot “multiply” a string and a
numeric value
24WDMD 170 – UW Stevens Point
Comparison Operators• Used to compare operands, perhaps for equality
or if the contents of a variable is greater than a literal value…– e.g. does myStatus equal “Accepted”?
myStatus == “Accepted”– or is myGPA greater than 3.0?
myGPA > 3.0 • Notice that we can use numeric or string values
as operands
• Notice that the answer (the result, in JS-speak) is either true or false. (a Boolean result)
26WDMD 170 – UW Stevens Point
Comparison Operator Examples
• The following example extends Gosselin’s examples on page 148.
• The file is available here: ComparisonOperators.htm
• You may wish to view it and save it for reference purposes.
27WDMD 170 – UW Stevens Point
Comparison Operator Examplesvar x = 5, y = 6;document.writeln("1 x is: " + x);document.writeln("2 y is: " + y);document.writeln("3 x == y is: " +(x == y));document.writeln("4 x != y is: " +(x != y));document.writeln("5 x > y is: " +(x > y));document.writeln("6 x < y is: " +(x < y));document.writeln("7 x <= y is: " +(x <= y));document.writeln();
x = "text string";y = "different string";document.writeln("8 x is: " + x);document.writeln("9 y is: " + y);document.writeln("10 x != y is: " +(x != y));
document.writeln('11 "abc" == "abc" is: ' + ("abc" == "abc"));document.writeln('12 "abc" == "xyz" is: ' + ("abc" == "xyz"));document.writeln();
x = 5;y = "5"; //note that y is a stringdocument.writeln("13 x is: " + x);document.writeln("14 y is: " + y);document.writeln("15 x == y is: " +(x == y));document.writeln("16 x != y is: " +(x != y));document.writeln("17 x === y is: " +(x === y));document.writeln("18 x !== y is: " +(x !== y));
1 x is: 5
2 y is: 6
3 x == y is: false
4 x != y is: true
5 x > y is: false
6 x < y is: true
7 x <= y is: true
8 x is: text string
9 y is: different string
10 x != y is: true
11 "abc" == "abc" is: true
12 "abc" == "xyz" is: false
13 x is: 5
14 y is: 5
15 x == y is: true
16 x != y is: false
17 x === y is: false
18 x !== y is: true
ComparisonOperators.htm
28WDMD 170 – UW Stevens Point
Conditional operator
• Executes one of two expressions, based on the results of a conditional expression– Syntax
• cond_expression ? expression1 : expression2;– If cond_expression = true expression1 executes– If cond_expression = false expression2 executes
– Example:•(BirthYear < 1986 ) ? document.writeln(“voting age”) : document.writeln(“cannot vote”);
29WDMD 170 – UW Stevens Point
Refer to the instructions on pages 149-50 (Gosselin).
• Create the file ComparisonExamples.htm and save it in your Tutorial03 folder.
• Preview the .htm file.
eTask 4
30WDMD 170 – UW Stevens Point
Logical Operators• Used for comparing two Boolean operands
for equality• Comparison returns a Boolean value• Comprised of both binary and unary
operators– Logical “and” is a binary operator
• (Expr1) && (Expr2)
– Logical “or” is a binary operator• (Expr1) || (Expr2)
– Logical “not” is a unary operator• !(Expr1)
32WDMD 170 – UW Stevens Point
Refer to the instructions on pages 153-4 (Gosselin).
• Create the file LogicalExamples.htm and save it in your Tutorial03 folder.
• Preview the .htm file.
eTask 5
33WDMD 170 – UW Stevens Point
Working with Strings
• JavaScript has two operators that can be used with Strings to combine two strings– Concatenation operator (+)
• var oneString = “one”;• var anotherString = oneString + “, two, three,
…”;
– Assignment operator (+=)• var oneString = “one”;• oneString += “, two, three, …”;
34WDMD 170 – UW Stevens Point
String Object
• Literal strings and string variables in JavaScript are represented by a String object
• The String object contains properties and methods for manipulating text strings– length– indexOf(string, [startingPos])– substring(starting index, ending index)
35WDMD 170 – UW Stevens Point
String Object Manipulations
Given: var myStr = “JavaScript”;
• length property– returns the number of characters in a stringdocument.writeln(myStr.length); //displays 10
• indexOf(smStr) method– returns the position number of a smStr within a
stringdocument.writeln(myStr.indexOf(“cri”)); //displays 5
• substring(startindex, endindex) method– returns the substring extracted from characters at
startindex through endindex from a larger stringdocument.writeln(myStr.substring(2,5)); //displays “vaS”
36WDMD 170 – UW Stevens Point
Refer to the instructions on pages 158-60 (Gosselin).
• Create the file StringExamples.htm and save it in your Tutorial03 folder.
• Preview the .htm file.
eTask 6
37WDMD 170 – UW Stevens Point
Operator Precedence
• Order of priority in which operations in an expression are evaluated
• Expressions are evaluated– On a left-to-right basis– With the highest priority precedence
evaluated first
38WDMD 170 – UW Stevens Point
Operator Precedence – in order
• Listed in order of precedence – Parentheses/brackets/dot ( ) [ ] .– Negation/increment ! - ++ -- typeof void– Multiplication/division/modulus * / %– Addition/subtraction + -– Comparison < <= > >=– Equality (equals and not equals) == !=– Logical AND &&– Logical OR ||– Assignment operators = += -= *= /= %=– Comma ,
39WDMD 170 – UW Stevens Point
• Carefully read the text “Creating the Calculator Program” on page 161.
• Refer to the instructions on pages 162-4 (Gosselin).
• Create the file Calculator.htm and save it in your Tutorial03 folder.
• Preview the .htm file.
<CONTINUED ON THE NEXT SLIDE>
eTask 7
40WDMD 170 – UW Stevens Point
Add the following to the calculator HTML document (below the calculator):
• Create at least 5 expressions to illustrate the order of operations (include the answer in your problem statement)
• Answer the following questions in your document (copy in the text of the question, then answer it):
1. Why doesn’t entering numbers from the keyboard work?2. Why is the variable inputString a global variable?3. What statement (and which function) does the actual
“calculating”?4. Give an explanation of how this thing works! In other words,
follow the code and pretend you’re explaining it to someone. Use an easy expression (e.g. 1+2*3) to guide your explanation.
eTask 7 cont’d
41WDMD 170 – UW Stevens Point
Assignment
• Complete exercise #3 page 169 (Gosselin, Tutorial 03B).
• Prepare your solution in the manner illustrated in ComparisonOperators.htm.
• Save the file as Tut03BExercise3.htm.
42WDMD 170 – UW Stevens Point
Assignment – Mixed ExpressionsCopy and paste* the following into an HTML document: (save
the file as mixedExpressions.htm) (*Or download the file mixedExpressions.htm)
<pre><script>document.writeln("'arithmetic' using numbers");document.writeln(6 + 2); // result is __ <fill this in>document.writeln(6 - 2); // result is __ document.writeln(6 * 2); // result is __document.writeln(6 / 2); // result is __
document.writeln("using numbers and digit strings with operators (other than +)");document.writeln(6 - "2"); // result is __ document.writeln("6" * 2); // result is __ document.writeln("6" / "2"); // result is __
document.writeln("using numbers and digit strings with +");document.writeln(6 + "2"); // result is __ document.writeln("6" + 2); // result is __ document.writeln("6" + "2"); // result is __
document.writeln("using numbers and char strings with operators");document.writeln("6" * "two");// result is __ (see page 143 of [G])document.writeln(6 * "two"); // result is __</script></pre>
<CONTINUED ON THE NEXT SLIDE>
43WDMD 170 – UW Stevens Point
Assignment – Mixed Expressions cont’d.
• Preview the file and fill in the blanks with each result
• Study the code!• Answer the following questions in your document.
(Copy in the text of the question, then answer it. The line numbers will be clear in the source code viewed in HTML-Kit.)
1. What seems to be happening in lines 16-18?2. Contrast the result from line 18 with the result from line
23. 3. What does JavaScript do when an arithmetic operator
(other than +) is placed between digit strings?4. Contrast the result from line 18 with the result from line
25.5. What does JavaScript do when + is placed between a digit
and a char string?