JavaScript – Part II Data Types and Operations George Mason University June 3, 2010.
-
Upload
nigel-walker -
Category
Documents
-
view
213 -
download
0
Transcript of JavaScript – Part II Data Types and Operations George Mason University June 3, 2010.
Identifiers
• A sequence of characters : letters, digits, underscores (_), and dollar signs ($).
• start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. • An identifier cannot be a reserved word.
• An identifier can be of any length.
• Used for variables, method names, function names
Variables
• Areas of memory
• Used to store values
• Given ‘names’ to refer to
25age
variable name location in RAM
value
Variables Types and Declarations
• Many programming languages require you to declare the type of the variable before you use it . This defines what type of information (integer, floating point number, etc.) can be stored in the variable
• JavaScript is what is known as a loosely-typed language; you don’t declare the type, and the type of what is stored in a variable can change during the program, e.g. holding a number, and later a string
document.write()
• document.write() is a method of the Document object (one refers to the object using a capital letter but the JavaScript always uses lower case)
• document.write() outputs the information inside of the parentheses as part of the web page at the point in which it is invoked
Outputting the Value of Variables into the Web Page
Variables displayed alone or with string • Ex1: document.write(billingDate); • Ex2: document.write("Next bill: October " +
billingDate);• String Concatenation: joins arguments with (+)
operator
Note: When the name of a variable is used (except on the left hand side of an =) the VALUE of the variable replaces it!)
Output Using Alert box
• The alert() method of the window object can also be used to display the value of variables, just like the write() method of the document object – the alert() method creates an alert box which stops rendering of the web page until the user clicks OK; because this is so intrusive and one often wants the output to be part of the web page, alert boxes are only used where getting the user's attention is important
• Use: window.alert("Hello") ; alert("Hello"); // window is understood
Assignment Statements
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
circum=radius; // Assign 1.0 to circum
Note: first the value of the expression on the right hand side of the equal sign is determined, then that quantity replaces the current value of the variable
Operators
• Arithmetic+ - * / %
• String – concatenation +• Comparison or Relational
> < >= <= != ==• Assignment (= ++ --)• Shortcut Assignment (+=,-=,*=,/=,%=)• Boolean (! && ||)
Arithmetic StatementsOperator precedence: rules ordering operation sequence
• Multiply, divide, and mod before add and subtract• Parentheses override normal precedence
Associativity: left to right for binary operators
Nested parentheses: evaluate from inside out
Example: 65 + 35 – (45 + 9) / 9 * 7• Evaluates to 58• Without parentheses: evaluates to 62 (do not distribute -)
• Parentheses are often used to clarify order of evaluation even when they don’t change it
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Boolean data type for variables
• boolean: holds one of two values: true or false• Example statements
• isItPayday = false;• areYouBroke = true;
• Six binary comparison operators • (==), (>), (<), (!=), (>=), (<=)• Results of operations: true or false
• Perform comparisons, assign results to variable • isSixBigger = (6 > 5); • isOTPay = (hours > 40);
Common Errors
• Misspelling of a keyword or variable name• Expression incorrectly written
• Missing ‘+’ in concatenation for output• Use of implied multiplication (e.g. in algebra,
variables next to each other are multiplied, e.g xy whereas one must write x*y in JavaScript)
Shortcut Assignment Operators
Operator Example Equivalent
+= i+=8 i = i+8
-= f-=8.0 f = f-8.0
*= i*=8 i = i*8
/= i/=8 i = i/8
%= i%=8 i = i%8
Increment andDecrement Operators
Operator Name Description++var preincrement The expression (++var) increments var by 1
and evaluates to the new value in var after the increment.
var++ postincrement The expression (var++) evaluates to the original value
in var and increments var by 1. --var predecrement The expression (--var) decrements var by 1
and evaluates to the new value in var after the decrement.
var-- postdecrement The expression (var--) evaluates to the original value
in var and decrements var by 1.
Increment andDecrement Operators, cont.
i = 10; newNum = 10 * i++;
newNum = 10 * i; i = i + 1;
Same effect as
i = 10; newNum = 10 * (++i);
i = i + 1; newNum = 10 * i;
Same effect as
Truth Table for Operator !
p !p
true false
false true
Example
!(1 > 2) is true, because (1 > 2) is false.
!(1 > 0) is false, because (1 > 0) is true.
Truth Table for Operator &&
p1 p2 p1 && p2
false false false
false true false
true false false
true true true
Example
(3 > 2) && (5 >= 5) is true, because (3 > 2) and (5 >= 5) are both true.
(3 > 2) && (5 > 5) is false, because (5 > 5) is false.
Truth Table for Operator ||
p1 p2 p1 || p2
false false false
false true true
true false true
true true true
Example
(2 > 3) || (5 > 5) is false, because (2 > 3) and (5 > 5) are both false.
(3 > 2) || (5 > 5) is true, because (3 > 2) is true.
Examples
document.write("Is " + num + " divisible by 2 and 3? " +
((num % 2 == 0) && (num % 3 == 0)));
document.write("Is " + num + " divisible by 2 or 3? " +
((num % 2 == 0) || (num % 3 == 0)));
Operator Precedence+, -, var++, var--, ++var,--var, ! (Not)
*, /, % (Multiplication, division, and remainder)
+,-(Binary addition/subtraction, String concatenation)
<, <=, >, >= (Comparison)
==, !=; (Equality)
&& (Conditional AND)
|| (Conditional OR)
?: Conditional operator (three operands)
=, +=, -=, *=, /=, %= (Assignment operator)
Using Input Dialog Boxes• Input dialog box: asks question above response field• prompt( ) used to create input dialog boxes
• result = prompt("Enter first number","default answer");
• The default answer displays initially in the textbox; if no second argument, one sees "undefined" there in Internet Explorer, nothing in Firefox
• The value returned will be treated as a string, even if the user entered a number
Conversion of Strings to Numbers
• Several ways to do this:• Multiply string by 1, or• Use parseInt(string value) or parseFloat(string
value) – both functions extract a number at the beginning of the string, ignoring non-numbers after that
Confirm Dialog BoxesConfirm dialog box displays options Ok, Cancel
Ex: selection = confirm("Do you want to upgrade to first class?");
the confirm() method returns either true (if user click OK), or false (if user clicked Cancel)
28
Appropriate Comments
Don’t overcomment by commenting the obvious; comments are for others and for you, to remind you what you were thinking
29
Naming Conventions
• Choose meaningful and descriptive names.
• Variables and method names: • Use lowercase. If the name consists of several
words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea.
Programming Errors
Syntax Errors• Detected by the interpreter when page loads
Runtime Errors• Causes a message to user about whether they
want to abort the program to abort
Logic Errors• Produces incorrect result