Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 1 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)
WHO AM I? Michael Kremer Federal Reserve Bank San Francisco Previously: Lawrence Berkeley National Laboratory Database/Application Developer Instructor for UC Extension since 1998 DB: Oracle, SQL Server, Access Programming: ASP.net, C#, VB/VBA, Java Web: Javascript, HTML, CSS Reporting: Cognos, Actuate
WHO ARE YOU? Name/Company/Organization What do you do? Computer Experience (OS, Application SW, Other Classes Taken, etc.) HTML, CSS, Programming Experience (if any) Expectations/Goals Any other information about you such as hobbies, special interests, fun facts, etc.
AGENDA 1. Introduction to JavaScript 2. Lexical Structure 3. (Data) Types
Introduction to JavaScript 1.
1.1 WHAT IS JAVASCRIPT 1 JavaScript is a modern, dynamic programming language It is a scripting language not compiled but interpreted JavaScript is not related to Java: Syntax (grammar) is derived from C Semantics (meaning) and design are influenced by Self and Scheme languages JavaScript is most commonly used as part of web browsers, whose implementations allow client-side scripts to: Interact with the user Control the browser Communicate asynchronously Alter the document content that is displayed JavaScript is also used in environments that are not web-based, such as PDF documents, site-specific browsers, and desktop widgets
1.2 HISTORY AND STANDARDIZATION OF JAVASCRIPT 2 JavaScript was originally developed at Netscape Communications Corporation Because Java was a competitor of C++ and aimed at professional programmers, Netscape also wanted a lightweight interpreted language that would complement Java by appealing to nonprofessional programmers, like Microsoft's Visual Basic JavaScript began to acquire a reputation for being one of the roadblocks to a cross-platform and standards-driven web In November 1996, Netscape announced that it had submitted JavaScript to ECMA International for consideration as an industry standard, and subsequent work resulted in the standardized version named ECMAScript JavaScript was criticized because its target were Web authors and other Amateurs With the advent of AJAX JavaScript became much more popular proliferation of comprehensive frameworks and libraries
1.3 FEATURES OF JAVASCRIPT 3 Imperative Programming Language: Statements that change a program state, define sequences of commands for the computer to perform, focuses on how (Declarative focuses on what. SQL) Structured Programming Language: Aimed at improving clarity, quality, and development time by making extensive use of subroutines, block structures and for and while loops, and no GoTo statements Dynamic: Types are associated with values, not with variables, JavaScript is almost entirely object-based Functional: Functions are first-class objects; they are objects themselves properties and methods (.call() and.bind()), higher order functions function arguments can be another function Prototype-based object-oriented programming: JavaScript uses prototypes where many other object-oriented languages use classes for inheritance. It is possible to simulate many class-based features with prototypes in JavaScript
1.4 CORE VS. CLIENT-SIDE JAVASCRIPT 4 JavaScript is a hosted programming language, meaning it does not exist on its own and must be executed in a host environment (web browser) The core JavaScript language defines a minimal API (Application Programming Interface) for working with text, arrays, dates, and regular expressions but does not include any input or output functionality responsibility of host environment First part of this course: Core JavaScript Second part of this course: JavaScript in a browser (HTML, CSS) Use browser built-in tools: Hands-on examples have been developed and tested using Firefox s Scratchpad Additional examples provided through Demo Examples App Use text editors (Notepad++) or more sophisticated tools to write JavaScript programs
1.4 CORE VS. CLIENT-SIDE JAVASCRIPT 5
1.4 CORE VS. CLIENT-SIDE JAVASCRIPT 6 Core JavaScript language includes the following basic components: Lexical structure Types, Values, Variables Expressions and Operators Statements Objects, Arrays Functions Pattern Matching with Regular Expressions Client-side JavaScript technology in modern web browsers: JavaScript in Web Browsers Window object, DOM object Scripting CSS Handling Events jquery library
Lexical Structure 2.
2.1 CHARACTER SET 7 JavaScript supports the Unicode character set: Unicode is a computing industry standard for the consistent encoding, representation, and handling of text expressed in most of the world's writing systems Two ways in which JavaScript handles Unicode source code: JavaScript source code is treated as a sequence of UTF-16 code units Any code unit can also be expressed via a Unicode escape sequence \uhhhh (HHHH = four hexadecimal digits) you can use Unicode characters in literals and variable names, without leaving the ASCII range in the source code
2.1 CHARACTER SET 8 Externally JavaScript source code is usually not stored in UTF-16 depends on the load process in the web browser Case Sensitivity JavaScript is a case-sensitive language!! online, Online, OnLine, ONLINE are four distinct variable names HTML is not case-sensitive! can be confusing when using JavaScript with HTML
2.1 CHARACTER SET 9 White Space, Line Breaks, and Format Control Characters JavaScript ignores spaces and line breaks between tokens in programs format your code using indentation and line breaks! In addition to the regular space character (\u0020), JavaScript also recognizes the following characters as whitespace: JavaScript recognizes the following characters as line termination characters:
2.2 COMMENTS 10 JavaScript supports two styles of comments:
2.3 LITERALS 11 Literals A data value that appears directly in a program (hard-coded): More complex expressions can serve as array and object literals:
2.4 IDENTIFIERS AND RESERVED WORDS 12 Identifiers are used to name variables and functions and to provide labels for certain loops in JavaScript code Naming rules: Legal identifiers: For portability and ease of editing, it is common to use only ASCII letters and digits in identifiers It is possible to use any Unicode character:
2.4 IDENTIFIERS AND RESERVED WORDS 13 JavaScript reserves certain identifiers for use by itself: Keywords reserved for future use (ECMA 6): When JavaScript is running in strict mode: Avoid JAVA keywords as well: Predefined global variables and functions: JavaScript implementations (i.e. web browser) may define other global variables and functions (window object, document object)
2.5 STATEMENT ENDING CHARACTERS 14 JavaScript uses the semicolon (;) to separate statements from each other You can usually omit the semicolon: Many programmers use explicit ; even if not required, others omit semicolons whenever possible: JavaScript treats a line break as a semicolon if the next nonspace character cannot be interpreted as a continuation of the current statement
2.5 STATEMENT ENDING CHARACTERS 15 Statement termination rules can lead to surprising cases: If a statement begins with (, [, /, +, or -, there is a chance that it could be interpreted as a continuation of the statement before Statements beginning with ( and [ are not uncommon at all, at least in some styles of JavaScript programming Therefore some programmers put defensive semicolons at the beginning of the line:
2.5 STATEMENT ENDING CHARACTERS 16 Two exceptions to the general rule that JavaScript interprets line breaks as semicolons when it cannot parse the second line as a continuation of the statement on the first line: Involves return, break, and continue statements JavaScript treats these statements as individual statements line break means ; Involves the ++ and operators
(Data) Types 3.
3.1 OVERVIEW OF TYPES 17 Computer programs work by manipulating values, such as the number 2.53 or the text This is a test. data types or types JavaScript types can be divided into two main categories: An object (that is, a member of the type object) is a collection of properties where each property has a name and a value (either a primitive value, such as a number or string, or an object) Object is an unordered collection, whereas an array is ordered Function is also an object, a function contains executable code Functions used with new keyword constructor Each constructor defines a class of objects Classes can be thought of as subtypes of the object type, or instances
3.1 OVERVIEW OF TYPES 18 In addition to function and array classes, core JavaScript contains 3 additional classes: Date, RegExp, Error JavaScript interpreter performs automatic garbage collection for memory management program can create objects as needed, and the programmer never needs to worry about destruction or deallocation of those objects JavaScript is an object-oriented language: Rather than having globally defined functions to operate on values of various types, the types themselves define methods for working with values Sort an array a: Not sort(a) but a.sort() JavaScript contains mutable and immutable types: Mutable, value can change: Objects and arrays are mutable Immutable, value cannot change: Numbers, Booleans, null, and undefined String is array of characters, also immutable JavaScript converts values liberally from one type to another JavaScript variables are untyped, assign any value into a variable
3.2 NUMBERS 19 No distinction between integer values and floating-point values All numbers are represented as floating-point values JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard can represent numbers as large as ±1.7976931348623157 10 308 and as small as ±5 10 324 Integer Literals In a JavaScript program, a base-10 integer is written as a sequence of digits: JavaScript recognizes hexadecimal (base-16) values A hexadecimal literal begins with 0x or 0X, followed by a string of hexadecimal digits A hexadecimal digit is one of the digits 0 through 9 or the letters a (or A) through f (or F), which represent values 10 through 15
3.2 NUMBERS 20 Floating-Point Literals Floating-point literals can have a decimal point; they use the traditional syntax for real numbers Floating-point literals may also be represented using exponential notation: a real number followed by the letter e (or E), followed by an optional plus or minus sign, followed by an integer exponent Arithmetic Operations JavaScript programs work with numbers using the arithmetic operators that the language provides: More complex mathematical operations: Math object
3.2 NUMBERS 21 Arithmetic in JavaScript does not raise errors in cases of overflow, underflow, or division by zero If a value is larger than what JavaScript can represent infinity or negative infinity If a value is smaller than what JavaScript can represent 0 Division by zero is not an error in JavaScript: it simply returns infinity or negative infinity Zero divided by zero does not have a well defined value: Result of this operation is the special not-a-number value, printed as NaN infinity/infinity, square root of negative number NaN
3.2 NUMBERS 22 NaN does not compare equal to any other value, including itself: Cannot write x == NaN to determine whether the value of a variable x is NaN Instead, you should write x!= x (x unequal x, true only if x is NaN) Function NaN(), returns true if argument is NaN/non-numeric value (string or objects) Related function isfinite() returns true if its argument is a number other than NaN, Infinity, or -Infinity The negative zero compares equal (even using JavaScript s strict equality test) to positive zero, which means that the two values are almost indistinguishable, except when used as a divisor Binary vs. Decimal Math There are infinitely many real numbers, but only a finite number of them can be represented exactly by the JavaScript floating-point format representation of the number will often be an approximation of the actual number
3.2 NUMBERS 23 IEEE-754 floating-point representation used by JavaScript is a binary representation exact ½, 1/8, 1/1024 but not 1/10 Plenty of precision can approximate 0.1 very closely, but yet not exact -> problems when comparing numbers! In general, precision is sufficient, but be aware when comparing numbers Future version might include decimal numerical type
3.3 DATES AND TIMES 24 Date() constructor for creating objects that represent dates and times Date objects have methods that provide an API for simple date computations Reference date is 1/1/1970 Called as function (Date(), without new) current date and time as a string not a Date object
3.3 DATES AND TIMES 25 No properties, all access to date and time values is done through methods Most methods come in two forms: Date methods can only be invoked on date objects, otherwise TypeError is thrown Many methods for Date/Time computation
3.4 TEXT 26 String is an immutable ordered sequence of 16-bit values, each of which typically represents a Unicode character strings are JavaScript s type for representing text Strings are zero-based arrays String Literals Enclose the characters of the string within a matched pair of single or double quotes JavaScript in HTML: Use different quotes for HTML and JavaScript
3.4 TEXT 27 Escaping in String Literals Backslash character (\) has a special purpose in JavaScript strings Combined with the character that follows it, it represents a character that is not otherwise representable within the string
3.4 TEXT 28 String Processing Concatenate strings using the + operator (strings are joined): Determine the length by using length property on a string: String is not an object but behaves like one as it does have builtin methods Remember that strings are immutable in JavaScript Methods like replace() and touppercase() return new strings: they do not modify the string on which they are invoked Strings can be treated like read-only arrays use array access methods (array[3]) as opposed to charat() method
3.4 TEXT 29