MCS-170 The Nature of Computer Science
Chapter 5
1. Review
2. Primitive data types in JavaScript
- Numbers
- No distinction is made between integers and floating-point
numbers
- Examples of numeric literals
3
3.15
6.02e23 // this means 6.02 times 10 to the 23rd power
- Strings
- A JavaScript string is any sequence of characters
- String literals
always appear between single or double quotes
- Examples of string literals
"Please enter your name"
"3.15"
"Mike Hvidsten"
"This is an example of a \" double-quote \" in a
string"
- Booleans
- The boolean type has two values, represented by the keywords
true
and false
3. Using Numbers
- Use the predefined function
parseFloat("3.15")
to convert a string ("3.15"
)
into its corresponding number (3.15
)
- But we must be careful about concatenation
"3.15" + "1"
evaluates to "3.151"
(string concatenation)
3.15 + 1
evaluates to 4.15
(numerical addition)
"3.15" + 1
evaluates to "3.151"
(string concatentation)
- Example to add two numbers (needs repair)
- Group Work - fix this program
4. Predefined functions
- JavaScript provides an extensive library of predefined functions
- Examples
document.write("x");
prompt("","");
parseFloat(x);
Math.sqrt(x);
- Math.max(y, y);
Math.random();
5. Expressions and operators
- Expressions are formed by combining values, which may be
literals, variables, function calls, array elements, or object
properties, using JavaScript operators
- Parentheses are used to group subexpressions and alter the
default order of evaluation of operators
1 + 2 * 3
is evaluated as 1 + (2 * 3)
- If you really want the addition done before the multiplication,
you should write
(1 + 2) * 3
6. Group Project
- Write a JavaScript program to prompt for two numbers x and y and
that writes out on the web page the square root of x*y.
- Add to your program a second output to the web page of the
maximum value of x and y.