Data Types and Operators Using Data Types
How to use data typesAbout numeric data typesAbout Boolean valuesHow to use JavaScript objectsHow to use stringsHow to use arrays
Using Data Types
• Data Types• Variables contain many different types of
values• e.g., time of day, person’s name, currency amount
• JavaScript variables are classified into categories known as data types
• Primitive data types• Data types that can be assigned only a single value• JavaScript supports five primitive data types
• Integers • Floating points• Booleans• Strings• Null
•Examples: Primitive Types folder
Primitive data typesNull value
Data type and a valueSignifies that the variable contains no value
Undefined variableHas never had a value assigned to itHas not been declared or Does not exist
Using Data Types
• Data Types• Reference (composite) data types
• Collections of data represented by a single variable name
• JavaScript supports three reference data types• Functions• Objects• ArraysStrongly typed programming languages
• Data types do not change after they have been declared (data type declaration required)
• Also know as static typing
Using Data Types
• Data Types• Loosely typed programming languages
• Variable data types are not required to be declared• Also know as dynamic typing
• JavaScript language• Loosely typed programming language• JavaScript does not allow data typing• Determined automatically by JavaScript interpreter
• Can be determined using typeof() operator• typeof(variableName)
Using Data Types
• Numeric Data Types• JavaScript supports two numeric data
types• Integers
• Positive or negative number with no decimal point• Range from –253 to 253
• Floating points• Contains decimal places or written using
exponential notation• Range from 1.7976931348623157 X 10308 to 5
X 10-324
• Boolean Values• Logical value of true or false
• Can be thought of as yes/on/1 or no/off/0• Used for decision making and comparing data
• Recall use in overriding internal event handler with custom code
• Strings• Text string contains zero or more characters delimited by double
or single quotation marks• Text strings can be:
• Used as literal values• Assigned to a variable• Assigned a zero-length string value (empty string)
• Using quotation marks and apostrophes• Use one to delimit and the other in the literal
• var thisString = “Dave’s house”;• var anotherString = ‘The “house” of Dave’;
• Or, use escape sequence• var aThirdString = ‘Dave\’s house’;
Using Data Types
• Strings• Using HTML tags in strings
• Use tags to format strings• Tag must be contained inside string quotes• var newString = “Dave’s house.<br>”;
HTML in document.writeln
• Best approach: create a string that contains the values.
var fFam = “Times”;var fSize = "24pt";
var fColor = "blue";var bColor = “cream”;var writer = “Ernest Hemmingway”;
var top =“<html><head></head>”;top + = "<body bgcolor=" + bColor;top += "><h1 style='font-family:" + fFam;
top += ";font-size:" + fSize + ";color:" + fColor + ";'>";
document.write(top + writer + " wrote \'Islands in the Stream\'.</h2>");
• Examples: html expressions folder
Using Data Types
• Arrays• Contains a set of data represented by a
single variable name• i.e., collection of variables contained in a single
variable• Used to store related things• To create, use Array() constructor function
• hospitalDepartments = new Array(numberOfElements);
• Arrays• Each piece of data in array is an element• Numbering of elements in array starts with 0• Size of array is declared and each element in array is accessed
using brackets [ ]• hospitalDepartments = new Array(10);• hospitalDepartments[0] = “Oncology”;
• Arrays can contain different data types• Array elements are undefined unless value is assigned • Array property length
• Returns the number of elements in the array
• var theSize = hospitalDepartments.length;
alert(“There are “ + theSize + “departments”);
• Examples: Arrays folder:• FamilyArray.html• InterestArray.html• MonthsOfYear.html• SongYears.html• StringExamples.html
Expressions and Operators• Expressions
• Combination of literal values, variables, operators, and other expressions that can be evaluated by the JavaScript interpreter to produce a result
Expressions and Operators• Expressions
• Operators and operands can be used to create more complex expressions
• Operand• Variables and literals contained in an expression
• Operators• Symbols used in expressions to manipulate
operands• Example:
• myNumber = 100;
• Operators• Can be binary or unary
• Binary• Requires an operand both before (left operand) and
after (right operand) the operator • e.g., myNumber = 100;
• Unary• Requires a single operand either before or after the
operator• e.g., myNumber++
• Arithmetic Operators• Used to perform mathematical calculations• Comprised of both binary and unary operators• Note:
• Addition operator (+), when used on strings concatenates the operands (operator overloading)
• Arithmetic Operators• Converting strings to integers:
• Reference: page 165 of JavaScript, the Definitive Guide.
• Can use the Number() built-in function:• var number = Number(string_value);• only works with base-10 numbers, does not allow
any non-space characters to appear in the string following the number
• Can use the parseInt() built-in function:•var number = parseInt(“3 blind mice”) ;• places the integer 3 into the var number• only works with any base number, converts any
number at the beginning of a string, ignores any non-number characters at the end.
• Can use the parseFloat() built-in function:• var number = parseFloat(“3.12 blind mice”) ;• places the value 3.12 into the var number• works with both integers and floating point
numbers.
• Precision: You can adjust the number of digits a number has with number.toPrecision()var n = 12345.6789
n.toPrecision(1) // returns 1e+4
n.toPrecision(3) // returns 1.23e+4n.toPrecision(5) // returns 12346: note rounding
n.toPrecision(7) // returns 12345.67n.toPrecision(10) // returns 12345.67890: note added zero
Expressions and Operators• Rounding: You can adjust a number by rounding with
Math.round(theNum);• Rounds a float number to nearest integer (.5 goes up).
var n = 12345.6789
theNum = Math.round(n);
// theNum now contains 12346
• Examples:• numInPrompt.html• simple expressions folder
• ArithmeticExamples.html• BirthInfo.html• ImprovedProgram.html
• Arithmetic Operators• Unary operators
• Prefix operator• Placed before the operand
• ++count• Value returned after operation
• Postfix operator• Placed after the operand
• count++• Value returned before operation
• Assignment Operators• Used for assigning a value to a variable• Basic assignment operator (=)
• Assign initial value to new variable• Assign a new value to an existing variable
• NaN• Not a Number• Returned when a mathematical expression
does not result in a numerical value
• Can access forms through JavaScript• Reference the form element by its name• Example:
Using numbers in forms
Using numbers in forms<HTML><HEAD><SCRIPT LANGUAGE="JavaScript">function calculate() {
var squareFeet, totalCost;squareFeet = parseInt(document.Estimator.width.value) *
parseInt( document.Estimator.length.value);totalCost = squareFeet * parseInt( document.Estimator.cost_per_foot.value);totalCost *= 1.25;alert("The total cost to carpet this room is $" + totalCost);
}</SCRIPT></HEAD><BODY><H1>Carpet Cost</H1><FORM NAME="Estimator"><P><B>Enter the width of the room in linear feet </B><INPUT TYPE="text”
NAME="width”><B>Enter the length of the room in linear feet </B><INPUT TYPE="text"
NAME="length"><B>Enter the cost per square foot of carpeting </B><INPUT TYPE="text"
NAME="cost_per_foot"> </P><INPUT TYPE="button" VALUE=" Calculate " onClick="calculate();” ></FORM></BODY></HTML>
Using numbers in forms
• When to use parseInt( )• If you immediately multiply a value
from a form element by a constant number don’t need parseInt:• var x = document.myForm.amt.value * 10
• If you add values from two fields together, must use parseInt:• var y = document.myForm.amt.value +
document.myForm.amt2.value;
• Examples• CarpetCost.html• ConvertTemperature.html
Comparison Operators
• Used to compare two operands for equality and if one numeric value is greater than another
• Can use number or string values as operands
• Always gives a boolean answer (true or false)
Comparison Operators
• Examples:5 == 7 gives false5 != 7 gives true5 < 7 gives true5 > 7 gives falsevar x = 5;var y = 7;x == y; gives falsex != y; gives truex < y; gives truex > y; gives false
Comparison Operators
• Examples:var x = “A”;var y = “b”;x == y; gives falsex != y; gives truex < y; gives truex > y; gives false
• Comparison Operators• Conditional operator
• Executes one of two expressions, based on the results of a conditional expression
• Syntax• cond_expression ? expression1 : expression2;
• If con_expression = true expression1 executes
• If con_expression = false expression2 executesLogical Operators
Used for comparing two Boolean operands for equalityComparison returns a Boolean valueComprised of both binary and unary operators
Logical Operators
• Examplesvar x = 5;var y = 7;var z = 9;x == y && y < z gives falsex == y || y < z gives true!(x == y); gives true
• 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, …”;
• String Object• Literal strings and string variables in JavaScript are
represented by a String object• The String object contains methods for manipulating
text strings
• String Object• length property
• Returns the number of characters in a stringVar x = “Ithaca College”;Document.writeln(x.length); // prints 14
• Parsing• Act of extracting characters or substrings from a larger
string
• Parsing using the split() built-in function• stringVariable.split(delimiter). Returns an array of
strings, created by splitting string into substrings at the boundaries specified by delimiter.
• String Object• Parsing using the split() built-in function.
• Example:var myVar = “John Barr”;
var newVar = myVar.split(“ “);
newVar contains [“John”, “Barr”]
• String Object• Parsing using the split() built-in function.
• Example:var myVar = “red;blue;green;yellow”;
var newVar = myVar.split(“;“);
newVar contains [“red”, “blue”.”green”,”yellow”]
• Example:• Arrays/StringExamples.html
• 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
• Operator Precedence• Parentheses/brackets/dot (( ) [ ] .)• Negation/increment (! - ++ -- typeof void)• Multiplication/division/modulus (* / %)• Addition/subtraction (+ -)• Comparison (< <= > >=)• Equality (== !=)• Logical AND (&&)• Logical OR (||)• Assignment operators (= += -= *= /= %=)• Comma (,)