Tutorial 3B - Expressions and Operators
Download
Report
Transcript Tutorial 3B - Expressions and Operators
WDMD 170
Internet Languages
eLesson:
Data Types and Operators
(NON Audio Version)
© Dr. David C. Gibbs
2003-04
WDMD 170 – UW Stevens Point
1
Tutorial 3
Data Types and Operators
Section B - Expressions and Operators
WDMD 170 – UW Stevens Point
2
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
WDMD 170 – UW Stevens Point
3
Expressions in JavaScript
• Expressions
1. A literal value – string, integer, floating point,
Boolean, or null
2. A variable – string, integer, floating point,
Boolean
3. A combination of literal values, variables –
where the values are combined to form
longer expressions
WDMD 170 – UW Stevens Point
4
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 expression
3. 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!]
WDMD 170 – UW Stevens Point
5
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 =
WDMD 170 – UW Stevens Point
6
Types of JavaScript Operators
WDMD 170 – UW Stevens Point
7
JS Operators by Type
Arithmetic
+, =, *, /, %
Assignment
=, +=, -=, *=, /=, %=
Comparison
==, !=, >, <, >=, <=, ===, !==
Logical
!, &&, ||
String
+, +=
WDMD 170 – UW Stevens Point
8
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
operator
myNumber++ (arithmetic – post-increment)
-3
(arithmetic – prefix negation)
WDMD 170 – UW Stevens Point
9
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!)
WDMD 170 – UW Stevens Point
10
Arithmetic Binary Operators
WDMD 170 – UW Stevens Point
11
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.
WDMD 170 – UW Stevens Point
12
eTask 1
• 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
Result
Result
Result
Result
after
after
after
after
after
addition = 150
division = 25
subtraction = 75
multiplication = 200
modulus = 4
Result after increment = 101
• After the calculations, add an explanation in your HTML
document indicating why number % 6 is 4.
WDMD 170 – UW Stevens Point
13
Unary Arithmetic Operators
Unary 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 “postincrement”
WDMD 170 – UW Stevens Point
14
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
WDMD 170 – UW Stevens Point
15
Operator ++
The code of Example 1
var count = 1;
document.writeln(++count);
The code of Example 2
var count = 1;
document.writeln(count++);
is equivalent to these statements:
var count = 1;
count = count + 1;
document.writeln(count)
is equivalent to these statements:
var count = 1;
document.writeln(count)
count = count + 1;
The output is: 2
The value in count is: 2
The output is: 1
The value in count is: 2
WDMD 170 – UW Stevens Point
16
eTask 2
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();
2. Below the </pre> tag in
your document (so your
explanation appears in the
document), explain how
and why the results differ.
var count = 3;
document.writeln("count is: " + count);
document.writeln("count++ is: " + count++);
document.writeln("count is: " + count);
document.writeln();
</script></pre>
WDMD 170 – UW Stevens Point
17
Assignment Operators =, +=
• Used for assigning a value to a variable
• Basic assignment operator (=)
– Assign initial value to new variable
var
discountRate = 0.10;
– Assign a new value to an existing variable
discountRate = 0.15;
– Assign the result of an expression
temperatureCels = 5/9*(temperatureFahr-32);
• Arithmetic assignment operator
– Provides a shorthand notation for common statements
sum = sum + 5;
sum += 5;
// is functionally the same as
// an abbreviated form
WDMD 170 – UW Stevens Point
18
List of Assignment Operators
WDMD 170 – UW Stevens Point
19
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
WDMD 170 – UW Stevens Point
20
+= applied to strings
WDMD 170 – UW Stevens Point
21
eTask 3
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.
WDMD 170 – UW Stevens Point
22
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
WDMD 170 – UW Stevens Point
23
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)
WDMD 170 – UW Stevens Point
24
Co
mp
aris
on
Ope
rato
rs
WDMD 170 – UW Stevens Point
25
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.
WDMD 170 – UW Stevens Point
26
Comparison Operator Examples
var x = 5, y = 6;
document.writeln("1
document.writeln("2
document.writeln("3
document.writeln("4
document.writeln("5
document.writeln("6
document.writeln("7
document.writeln();
x
y
x
x
x
x
x
is: " + x);
is: " + y);
== y is: " +(x == y));
!= y is: " +(x != y));
> y is: " +(x > y));
< y is: " +(x < y));
<= y is: " +(x <= y));
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
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
document.writeln("13
document.writeln("14
document.writeln("15
document.writeln("16
document.writeln("17
document.writeln("18
1 x is: 5
y
x
y
x
x
x
x
is a string
is: " + x);
is: " + y);
== y is: " +(x == y));
!= y is: " +(x != y));
=== y is: " +(x === y));
!== y is: " +(x !== y));
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
WDMD 170 – UW Stevens Point
27
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”);
WDMD 170 – UW Stevens Point
28
eTask 4
Refer to the instructions on pages 14950 (Gosselin).
• Create the file
ComparisonExamples.htm and save it
in your Tutorial03 folder.
• Preview the .htm file.
WDMD 170 – UW Stevens Point
29
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)
WDMD 170 – UW Stevens Point
30
Logical Operators
WDMD 170 – UW Stevens Point
31
eTask 5
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.
WDMD 170 – UW Stevens Point
32
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, …”;
WDMD 170 – UW Stevens Point
33
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)
WDMD 170 – UW Stevens Point
34
String Object Manipulations
Given:
var myStr = “JavaScript”;
• length property
– returns the number of characters in a string
document.writeln(myStr.length);
• indexOf(smStr) method
//displays 10
– returns the position number of a smStr within a string
document.writeln(myStr.indexOf(“cri”));
//displays 5
• substring(startindex, endindex) method
– returns the substring extracted from characters at
startindex through endindex from a larger string
document.writeln(myStr.substring(2,5)); //displays “vaS”
WDMD 170 – UW Stevens Point
35
eTask 6
Refer to the instructions on pages 15860 (Gosselin).
• Create the file StringExamples.htm and
save it in your Tutorial03 folder.
• Preview the .htm file.
WDMD 170 – UW Stevens Point
36
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
WDMD 170 – UW Stevens Point
37
Operator Precedence – in order
• Listed in order of precedence
–
–
–
–
–
–
–
–
–
–
Parentheses/brackets/dot
Negation/increment
Multiplication/division/modulus
Addition/subtraction
Comparison
Equality (equals and not equals)
Logical AND
Logical OR
Assignment operators
Comma
( ) [ ] .
! - ++ -- typeof void
* / %
+ < <= > >=
== !=
&&
||
= += -= *= /= %=
,
WDMD 170 – UW Stevens Point
38
eTask 7
• 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>
WDMD 170 – UW Stevens Point
39
eTask 7 cont’d
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.
2.
3.
4.
Why doesn’t entering numbers from the keyboard work?
Why is the variable inputString a global variable?
What statement (and which function) does the actual
“calculating”?
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.
WDMD 170 – UW Stevens Point
40
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.
WDMD 170 – UW Stevens Point
41
Assignment – Mixed Expressions
Copy 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>
WDMD 170 – UW Stevens Point
42
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?
WDMD 170 – UW Stevens Point
43
End of eLesson
• Here is an excellent reference site entitled for the
material covered in this eLesson:
Data Types and Expressions
• Jump to the Beginning of this eLesson
• WDMD 170 Course Schedule
• D2L Courseware Site
WDMD 170 – UW Stevens Point
44