Download presentation

Presentation is loading. Please wait.

Published byAriana Casey Modified over 2 years ago

1
Data Types and Operators Using Data Types How to use data types About numeric data types About Boolean values How to use JavaScript objects How to use strings How to use arrays

2
Using Data Types Data Types Variables contain many different types of values e.g., time of day, persons 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

3
Examples: Primitive Types folder Primitive data types Null value Data type and a value Signifies that the variable contains no value Undefined variable Has never had a value assigned to it Has not been declared or Does not exist

4
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 Arrays Strongly typed programming languages Data types do not change after they have been declared (data type declaration required) Also know as static typing

5
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)

6

7
Using Data Types Numeric Data Types JavaScript supports two numeric data types Integers Positive or negative number with no decimal point Range from –2 53 to 2 53 Floating points Contains decimal places or written using exponential notation Range from X to 5 X

8
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 = Daves house; var anotherString = The house of Dave; Or, use escape sequence var aThirdString = Dave\s house;

9

10

11

12

13
Using Data Types Strings Using HTML tags in strings Use tags to format strings Tag must be contained inside string quotes var newString = Daves house. ;

14 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 = ; top + = "

15
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);

16

17
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);

18
Examples: Arrays folder: FamilyArray.html InterestArray.html MonthsOfYear.html SongYears.html StringExamples.html

19
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

20
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;

21

22
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)

23
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.

24
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 = n.toPrecision(1)// returns 1e+4 n.toPrecision(3)// returns 1.23e+4 n.toPrecision(5)// returns 12346: note rounding n.toPrecision(7)// returns n.toPrecision(10)// returns : note added zero

25
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 = theNum = Math.round(n); // theNum now contains 12346

26

27
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

28
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

29

30
Can access forms through JavaScript Reference the form element by its name Example: Using numbers in forms

31
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); } Carpet Cost Enter the width of the room in linear feet Enter the length of the room in linear feet Enter the cost per square foot of carpeting

32
Using numbers in forms When to use parseInt( ) If you immediately multiply a value from a form element by a constant number dont 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;

33
Examples CarpetCost.html ConvertTemperature.html

34
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)

35

36
Comparison Operators Examples: 5 == 7gives false 5 != 7gives true 5 < 7gives true 5 > 7 gives false var x = 5; var y = 7; x == y;gives false x != y;gives true x < y;gives true x > y;gives false

37
Comparison Operators Examples: var x = A; var y = b; x == y;gives false x != y;gives true x < y;gives true x > y;gives false

38
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 executes Logical Operators Used for comparing two Boolean operands for equality Comparison returns a Boolean value Comprised of both binary and unary operators

39

40
Logical Operators Examples var x = 5; var y = 7; var z = 9; x == y && y < zgives false x == y || y < zgives true !(x == y);gives true

41
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

42
String Object length property Returns the number of characters in a string Var 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]

43
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

44
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 (,)

Similar presentations

© 2016 SlidePlayer.com Inc.

All rights reserved.

Ads by Google