Data Types and Operators Using Data Types

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

COMP 14 Introduction to Programming
Operators and Expressions Operators are symbols that produce a result based on some rules. Examples: +, -, =, > and
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Using Data Types (No Audio Component) © Dr. David C. Gibbs
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Introduction to Scripting.
PHP Introduction.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
10 November JavaScript. Presentation Hints What do YOU think makes a good presentation Some of my suggestions Don’t write full sentences on slides Talk,
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Tutorial 11 Working with Operators and Expressions
JavaScript, Fourth Edition
Chapter 2 Data Types, Declarations, and Displays
ASP.NET Programming with C# and SQL Server First Edition
JavaScript, Third Edition
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Data Types and Operators (NON Audio Version) © Dr. David C. Gibbs
WEB DESIGN AND PROGRAMMING Introduction to Javascript.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Data Types.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Input, Output, and Processing
1 Working with Data Types and Operators. 2 Using Variables and Constants The values stored in computer memory are called variables The values, or data,
Chapter 2: Using Data.
C Derived Languages C is the base upon which many build C++ conventions also influence others *SmallTalk is where most OOP comes Java and Javascript have.
C++ Programming: Basic Elements of C++.
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Data Types Declarations Expressions Data storage C++ Basics.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Fluency with Information Technology Third Edition by Lawrence Snyder Chapter.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
PHP Programming with MySQL Slide 3-1 CHAPTER 3 Working with Data Types and Operators.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Chapter 14 JavaScript: Part II The Web Warrior Guide to Web Design Technologies.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Introduction to JavaScript 21 Introduction to Programming the WWW I CMSC Winter 2004 Lecture 15.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
REEM ALMOTIRI Information Technology Department Majmaah University.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 6 JavaScript: Introduction to Scripting
JavaScript, Sixth Edition
Overview: Programming Concepts
Introduction to Scripting
JavaScript Syntax and Semantics
Java Programming: From Problem Analysis to Program Design, 4e
Objectives Insert a script element Write JavaScript comments
Introduction to C++ Programming
Chapter 8 JavaScript: Control Statements, Part 2
WEB PROGRAMMING JavaScript.
Chapter 2: Basic Elements of Java
JavaScript Data Concepts
T. Jumana Abu Shmais – AOU - Riyadh
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

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

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

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

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

Using quotation marks and apostrophes 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 Combination of literal values, variables, operators, and other expressions that can be evaluated by the JavaScript interpreter to produce a result

Expressions and Operators 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)

Can use the parseInt() built-in function: 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+4 n.toPrecision(5) // returns 12346: note rounding n.toPrecision(7) // returns 12345.67 n.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: Arithmetic Operators 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

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

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&nbsp</B><INPUT TYPE="text” NAME="width”> <B>Enter the length of the room in linear feet&nbsp</B><INPUT TYPE="text" NAME="length"> <B>Enter the cost per square foot of carpeting&nbsp</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 false 5 != 7 gives true var x = 5; var y = 7; x == y; gives false x != y; gives true x < y; gives true x > y; gives false

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

Logical Operators 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

Logical Operators Examples var x = 5; var y = 7; var z = 9; x == y && y < z gives false x == 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 (+=) 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 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. Parsing using the split() built-in function. Example: var myVar = “John Barr”; var newVar = myVar.split(“ “); newVar contains [“John”, “Barr”]

Arrays/StringExamples.html 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”] Arrays/StringExamples.html

Parentheses/brackets/dot (( ) [ ] .) 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 Parentheses/brackets/dot (( ) [ ] .) Negation/increment (! - ++ -- typeof void) Multiplication/division/modulus (* / %) Addition/subtraction (+ -) Comparison (< <= > >=) Equality (== !=) Logical AND (&&) Logical OR (||) Assignment operators (= += -= *= /= %=) Comma (,)