JAVASCRIPT AND JQUERY: AN INTRODUCTION
(WEB PROGRAMMING, X452.1)
Professional Program: Data Administration and Management
Instructor: Michael Kremer, Ph.D.Technology & Information Management
Class 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, AccessProgramming: 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
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
1.2 HISTORY AND STANDARDIZATION OF JAVASCRIPT
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
Microsoft script technologies included VBScript and Jscript, Microsoft’s version of JavaScript used in Internet Explorer
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
2
1.3 FEATURES OF JAVASCRIPT
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, which can be changed at run-time
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
3
1.4 CORE VS. CLIENT-SIDE JAVASCRIPT
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 beendeveloped 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
4
1.4 CORE VS. CLIENT-SIDE JAVASCRIPT
5
1.4 CORE VS. CLIENT-SIDE JAVASCRIPT
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
6
Lexical Structure
2.
2.1 CHARACTER SET
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
7
2.1 CHARACTER SET
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
8
2.1 CHARACTER SET
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:
9
2.2 COMMENTS
JavaScript supports two styles of comments:
10
2.3 LITERALS
Literals
A data value that appears directly in a program (hard-coded):
More complex expressions can serve as array and object literals:
11
2.4 IDENTIFIERS AND RESERVED WORDS
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:
12
2.4 IDENTIFIERS AND RESERVED WORDS
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)
13
2.5 STATEMENT ENDING CHARACTERS
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
Whichever style you choose,be aware of pitfalls:
JavaScript treats a line breakas a semicolon if the next nonspace character cannot be interpreted as a continuation of the current statement
14
2.5 STATEMENT ENDING CHARACTERS
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:
15
2.5 STATEMENT ENDING CHARACTERS
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
16
(Data) Types
3.
3.1 OVERVIEW OF TYPES
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
17
3.1 OVERVIEW OF TYPES
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
18
3.2 NUMBERS
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, represent numbers as
Large as ±1.7976931348623157 × 10308
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
19
3.2 NUMBERS
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
20
3.2 NUMBERS
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
21
3.2 NUMBERS
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 NaNInstead, 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 trueif its argument is a number other thanNaN, 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
22
3.2 NUMBERS
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
23
3.3 DATES AND TIMES
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
24
3.3 DATES AND TIMES
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
25
3.4 TEXT
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
26
3.4 TEXT
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
27
3.4 TEXT
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 built-
in 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
28
3.4 TEXT
29