Title: Representation and Management of Data on the Web
1Javascript
- Representation and Management of Data on the Web
2Overview
- A "scripting" language for HTML pages
- Embed code in HTML pages so they are downloaded
directly to browser - The browser interprets and executes the script
(it is not compiled) - Do not declare data types for variables (loose
typing) - Dynamic binding object references checked at
runtime
3Overview (cont.)
- Scripts can manipulate "browser objects"
- HTML form elements
- Images
- Frames
- etc.
- For security cannot write to disk (when run on
a client)
4Abilities
- Generating HTML content dynamically
- Monitoring and responding to user events
- Validate forms before submission
- Manipulate HTTP cookies
- Interact with the frames and windows of the
browser - Customize pages to suit users
5It is not Java
- Java
- compilation required (not a script)
- can create stand alone application
- object-oriented
- Why is it called Javascript then?
6Web Architecture for JavaScript
"CLIENT"
"SERVER"
Desktop access
Remote host
Web browser
Web (HTTP) Server
HTML Page ltSCRIPTgt code.. lt/SCRIPTgt
Internet
HTML/HTTP TCP/IP
HTML/HTTP TCP/IP
built-in JavaScript interpreter
HTML pages w/ embedded script
7Example
Why do we need ltbrgt if we used writeln?
- ltHTMLgt
- ltHEADgtltTITLEgtAn Hello World Examplelt/TITLEgt
- ltSCRIPT LANGUAGE "JavaScript"gt
- document.write("ltfont size'4'gt")
- document.writeln("Hello World!ltbrgt")
- document.writeln("What a boring
examplelt/fontgt") - lt/SCRIPTgt
- lt/HEADgt
- ltBODYgt lt!-- An empty document body --gt lt/BODYgt
- lt/HTMLgt
RESULT
8Example
- ltHTMLgt
- ltHEADgtltTITLEgtAn Hello World Examplelt/TITLEgt
- ltSCRIPT LANGUAGE "JavaScript"gt
- document.write("ltfont size'4'gt")
- document.writeln("Hello World!ltbrgt")
- document.writeln("What a boring
examplelt/fontgt") - lt/SCRIPTgt
- lt/HEADgt
- ltBODYgt lth1gtMy Hello World Examplelt/h1gt lt/BODYgt
- lt/HTMLgt
RESULT
9Past and Present
- Built into Netscape Navigator since v2.0 (early
1996) - Developed independently of Java
- Proprietary, but submitted as standard and built
into Microsoft IE 3.0 and later - Standardized by ECMA (European Computer
Manufactures Association) into ECMAscript - EMCAscript joins JavaScript and Jscript to one
standard
10Client and Server
- JavaScript can be used
- On the client side
- On the server
- More lightweight and reliable on clients than
Java (Applets) - Useful for developing interactive interface
(Dynamic HTML)
11CGI and other Server-side Architectures
- Strengths
- allows access to server files and databases
- makes no assumptions about client computer
capabilities, puts little burden on it - easier to manage and control on server
- more secure for client
- Weaknesses
- puts most of processing load on server
- requires round-trip for every submission, using
valuable bandwidth - cannot provide instantaneous response expected
with GUI - less secure for server
12JavaScript Reserved Keywords
- break
- case
- continue
- delete
- do
- else
- false
- for
- function
- if
- in
- new
- null
- return
- switch
- this
- true
- typeof
- var
- void
- while
- with
13Non Used Reserved Words
- catch
- class
- const
- debugger
- default
- enum
- export
- extends
- finally
- import
- super
- try
14Javascript Variables
- Untyped!
- Can be declared with var keyword
- var foo
- Can be created automatically by assigning a
value - val 1
- val Thank for all the fish"
val has changed from an int to a String!
15Variables Names
- A variable name can be any valid identifier
- The identifier is a series of characters
- Consisting of letters (lower and upper case),
digits, and underscores (_) - Does not begin with a digit
- Does not contain any space
- Javascript is case sensitive (foo and FOO are
different)
16Variables
- Local variable is available only in the function
where it is declared - Global variable is available all over the
document - A variable declaration
- Inside a function creates a local variable
- Outside a function creates a global variable
- Local variables must be declared with var
17Literals
- The typical bunch
- Numbers 17 123.45
- Strings Let it be
- Boolean true false
- Arrays 1,ab ba,17.234
- null
- undefined
You can use typeof(A) to get the type of
A number, string, object..
18Operators
- Arithmetic, comparison, assignment, bit wise,
Boolean (pretty much just like Java) - - / --
- ! gt lt gt lt
- ! ltlt gtgt
- - /
19The Special Plus Command
- Which of the following two is correct?
- What is the type of the answer?
x The answer is 42 y 42 is the answer
20Which is correct?
- Which of the following two is correct?
- What is the type of the answer?
x "37" 7 y "37" - 7
21Types of Equality
- The equals checks if both operands are equal
after performing type conversion - The equals checks if both operands are of the
same type and equal - Example
- 3 "3" (true or false?)
- 3 "3" (true or false?)
22Types of Inequality
- The equals ! checks if both operands are unequal
after performing type conversion - The equals ! checks if both operands are not of
the same type and or not equal - Example
- 3 ! "3" (true or false?)
- 3 ! "3" (true or false?)
23Conditional Operators
- equals
- if (a b)
- not equals
- if (a ! b)
- greater than or equal to
- if (a gt b) ...
- less than or equal to
- if (a lt b) ...
24Boolean Operators
- and
- if (true true)
- or
- if (true false)
- not
- if (! false) ...
25- ltHTMLgt
- ltHEADgtltTITLEgtUsing Variableslt/TITLEgt
- ltSCRIPT LANGUAGE "JavaScript"gt
- var firstNumber 11,
- secondNumber 23,
- sum
- sum firstNumber secondNumber
- document.write("ltFONT COLOR 'blue' SIZE
'6'gtThe sum of " firstNumber " and "
secondNumber " is lt/FONTgt") - document.write(" ltFONT COLOR red' SIZE
'7'gt" sum "lt/FONTgt") - lt/SCRIPTgt
- lt/HEADgt
- ltBODYgt lt!-- An empty document body --gt lt/BODYgt
- lt/HTMLgt
RESULT
26Control Structures
- Some just like Java
- if if-else ? switch
- for while do-while
- And a few not like in Java
- for (var in object)
- with (object)
27JavaScripts Basic Constructs
- sequence (block)
- condition (selection)
- loop (iteration)
28JavaScript Constructs
- sequence (block)
- executes with no conditions
- semicolons optional using one statement per line,
but not a bad thing to use all the time - var metushelahAge 130 var yourAverageAge
- yourAverageAge metushelahAge - 98
- var myObject new Object("initial value")
- more statements here..
- ..
29JavaScript Constructs
- condition (selection)
- if (condition) statements if true
- else statements if false
- if (metushelahAge lt yourAverageAge)
- document.write ("ltbodygtlth2gtits true that
- Metushelah is younger than most of you,")
- document.write ("ltbrgtcomputers never lie!lt/h2gt
- lt/bodygt")
30JavaScript Constructs
- loop (iteration) both for and while loops are
available - for (var i0 i lt inputAge.length i)
- var oneChar inputAge.substring (i, i1)
- if (oneChar lt "0" oneChar gt "9")
- alert("Please enter a valid number
- oneChar " is not valid.")
-
31- ltHTMLgt
- ltHEADgtltTITLEgtLoops Examplelt/TITLEgt
- ltSCRIPT LANGUAGE "JavaScript"gt
- for (var counter 1 counter lt 8 counter)
- document.write(ltPgtltFONT COLOR blue SIZE
counter 'gt Now with font size " counter
" lt/FONTgtlt/Pgt ) -
- lt/SCRIPTgt
- lt/HEADgt
- ltBODYgt lt!-- An empty document body --gt lt/BODYgt
- lt/HTMLgt
RESULT
32JavaScript Functions
- Functions are first class citizens
- The keyword function used to define a function
(subroutine) - function add(x,y)
- return(xy)
33Function Input and Outout
- Numbers and Boolean values always passed to
functions using call-by-value - For objects, a call-by-reference is used to pass
them to the functions - Numbers and Boolean values are always returned by
value - Objects returned by reference
34Example
- Computing the Fibonacci numbers.
HTML Page
35- ltHTMLgt
- ltHEADgtltTITLEgtFunctions Examplelt/TITLEgt
- ltSCRIPT LANGUAGE "JavaScript"gt
- function fibonacciValue()
- var value parseInt(document.fibonacciForm.nu
mber.value ) - window.status "Calculating Fibonacci number
for " value - document.fibonacciForm.result.value
fibonacci(value) - window.status "Done Calculating Fibonacci
number" -
- function fibonacci( n )
- if (n 0 n 1) return n
- else return fibonacci( n - 1 ) fibonacci( n
- 2 ) -
- lt/SCRIPTgtlt/HEADgt
36- ltBODYgt
- ltFORM NAME "fibonacciForm"gt
- ltTABLE BORDER "1" BGCOLOR "blue"gt
- ltTRgtltTD BGCOLOR "cyan"gtEnter a numberlt/TDgt
- ltTDgtltINPUT NAME "number" TYPE
"text"gtlt/TDgt - ltTDgtltINPUT TYPE "button" VALUE
"Calculate" - ONCLICK "fibonacciValue()"lt/TR
gt - ltTRgtltTD BGCOLOR "cyan"gtFibonacci Valuelt/TDgt
- ltTDgtltINPUT NAME "result" TYPE "text"gt
lt/TDgt lt/TRgt - lt/TABLEgt
- lt/FORMgt
- lt/BODYgt
- lt/HTMLgt
RESULT
37Function Arguments
- Within a function, its arguments can be accessed
with argumentsi. - The number of arguments is arguments.length
- A function can be created that takes any number
of arguments
38Example
- function myConcat(separator) result"" //
initialize list // iterate through
arguments for (var i1 iltarguments.length
i) result argumentsi
separator return result - //What does this return?
- myConcat(", ","red","orange","blue")
39Global Functions (1)
- escape changes characters in a string that are
not in the ASCII characters set to HEX - unescape decodes the escape encoding
- eval gets a string of JavaScript code,
evaluates it and executes it - It allows dynamic code execution
40Global Functions (2)
- isNaN takes a numeric argument and returns true
if the value is not a number - parseFloat takes a string argument and converts
its beginning to a float number (or return NaN) - parseInt takes a string argument and converts
its beginning to an integer number (or return NaN)
41Global Functions (3)
- isFinite given a numeric argument it returns
true if the argument is not - NaN
- Number.POSITIVE_INFINITY
- Number.NEGATIVE_INFINITY
42Objects
- Objects have attributes and methods
- There are pre-defined objects and user-defined
object types - Using objects has similarity to the syntax of
C/Java
objectName.attributeName objectName.methodName()
43Objects Are Like Arrays
myCar.make "Ford" myCar.model
"Mustang" myCar.year 66
- myCarmake "Ford"
- myCarmodel "Mustang"
- myCaryear 66
44 function show_props(obj, obj_name) var
result "" for (var i in obj) result
obj_name "." i " "
obji "\n" return result
So, the function call show_props(myCar,
"myCar") would return the following
myCar.make Ford myCar.model
Mustang myCar.year 66
45Creating a New Object
- There are two ways to create new objects
- Object Initializer
- objectNameprop1val1, , propNvalN
- Constructor Function
- define a constructor function
- create the new object using new
46Example
function car(make, model, year) this.make
make this.model model this.year year
theMazda new car(Mazda", 323", 1991) theHonda
makeHonda, year1992,
color"red",wheels4, enginecylinders4,size2
.2
47Creating a Method
- A method of an object is a function that has been
assigned to the object
object.methodName functionName
48Example
function displayCar() var result "A
Beautiful " this.year " " this.make "
" this.model document.writeln(result)
function car(make, model, year) this.make
make this.model model this.year year
this.displayCar displayCar
49Eval Example
function Dog(name,breed,color)
this.namename this.breedbreed
this.colorcolor myDog new
Dog("Gabby") myDog.breed"Lab" var
breed'Shepherd' document.write("ltPgt"
eval('breed')) document.write("ltBRgt"
myDog.eval('breed'))
50Eval Example
function stone(str) eval("this."str)
this.y43 this"z" 44 flint new
stone("x42") document.write("ltBRgtflint.x is "
flint.x) document.write("ltBRgtflint.y is "
flint.y) document.write("ltBRgtflint.z is "
flint.z)
51Deleting an Object
- To delete an object just set the object reference
to null - When are objects that are not set to null being
removed?
52Array Objects
- Arrays are supported as objects
- Attribute length
- Methods include
- concat, join, pop, push, reverse, sort
53Creating a New Array
- var a red, blue, green
- Allocates an array of 3 cells and initializes the
values - var b new Array(5)
- Allocates an array of 5 cells without
initializing values - var c new Array()
- Creates a new empty array
54Array Example Code
var a 8,7,6,5 for (i0ilta.lengthi) ai
2 b a.reverse()
55Understanding Arrays
- Array literals
- arr1 "hello", 1, 33
- Accessing arrays (what is the result of)
- document.writeln(arr1.length)
- document.writeln(arr10)
- document.writeln(arr1"abc")
- arr11066
- document.writeln(arr1.length)
56Passing Arrays to Functions
- Arrays can be passed to functions as arguments
- The array is passed by call-by-reference
- The name of the array is given to the function
57- ltHTMLgtltHEADgtltTITLEgtArrays Examplelt/TITLEgt
- ltSCRIPT LANGUAGE "JavaScript"gt
- function start()
- var colors "red", "blue", "green"
- printArray(colors)
- printArray(colors)
-
- function printArray( arr)
- for (var i in arr)
- document.writeln("ltFONT SIZE5 COLOR"
arri "gt" - arri " lt/FONTgtltBRgt")
- arri "gray"
-
- lt/SCRIPTgt
- lt/HEADgtltBODY ONLOAD "start()"gt lt/BODYgtlt/HTMLgt
RESULT
58Multidimentional Arrays
- var matrix 0, 1, 1, 1, 1, 0, 0, 0, 0
- var myArray 1, 2, 3, 1, 1, 2
- Going over the array
- for (var i in myArray )
- for (var j in myArrayi)
- document.write(myArrayij)
59Other Object Types
- String manipulation methods
- Math trig, log, random numbers
- Date date conversions
- RegExp regular expressions
- Number limits, conversion to string
60Math Common Methods
- abs(x)
- round(x)
- ceil(x)
- floor(x)
- max(x, y)
- min(x, y)
- cos(x)
- sin(x)
- tan(x)
- exp(x)
- pow(x, y)
- sqrt(x)
- log(x)
Math Also includes constants such as Math.E,
Math.PI
61String Common Methods
- charAt (index)
- charCodeAt(index)
- concat(string)
- fromCharCode(value1, value2, )
- indexOf(substring, index)
- lastIndexOf(substring, index)
- slice(start, end)
- split(string)
- substr(start, length)
- substring(start, end)
- toLowerCase()
- toUpperCase()
- toString()
- valueOf()
62Methods that Generate HTML
- anchor(name) wraps the source with
- ltA name namegtlt/Agt
- big() wraps the source with
- ltBIGgtlt/BIGgt
- blink() wraps with
- ltBLINKgtlt/BLINKgt
- bold() wraps the source with
- ltBgtlt/Bgt
- fixed() wraps the source with
- ltTTgtlt/TTgt
63More Methods that Generate HTML
- fontcolor(color) wraps with
- ltFONT colorcolorgtlt/FONTgt
- fontsize(size) wraps with
- ltFONT sizesizegtlt/FONTgt
- italic() wraps with
- ltIgtlt/Igt
- link(url)
- ltA href urlgtlt/Agt
64More Methods that Generate HTML
- small() wraps the source with
- ltSMALLgtlt/SMALLgt
- strike() wraps the source with
- ltSTRIKEgtlt/STRIKEgt
- sub() wraps the source with
- ltSUBgtlt/SUBgt
- sup() wraps the source with
- ltSUPgtlt/SUPgt
65Date Common Methods
- getDate(), getFullYear(), getMonth(), getDay
- getTime(), getHours(), getMinutes(),
getSeconds(), getMilliseconds()
66- ltHTMLgt
- ltHEADgtltTITLEgtTime Examplelt/TITLEgt
- ltSCRIPT LANGUAGE "JavaScript"gt
- function getTimes()
- var current new Date()
- var out "Day " current.getDay()"\n"
- out out.concat("Month "
current.getMonth() "\n") - out out.concat("Year "
current.getFullYear() "\n") - out out.concat("GMT Time "
current.toUTCString() "\n") - out out.concat("Time "
current.toString() "\n") - timesForm.output.value out
-
- lt/SCRIPTgt
- lt/HEADgt
67RESULT
- ltBODYgt
- ltFORM NAME"timesForm"gt
- ltPgt
- ltINPUT NAME "getTimeButton" TYPE "button"
VALUE "Get Time" ONCLICK "getTimes()"gt - ltPgt
- ltTEXTAREA NAME "output" ROWS "10" COLS"42"gt
- lt/TEXTAREAgt
- lt/FORMgt
- lt/BODYgt
- lt/HTMLgt
68Predefined Objects
- In JavaScript the following objects are
automatically created for you (always available) - document
- navigator
- screen
- window
69The document Object
- Many attributes of the current document are
available via the document object - Title Referrer
- URL Images
- Forms Links
- Colors
70Objects Hierarchy
- JavaScript objects include object hierarchy
(property or method) - window.document.lastModified
- metushelahBirthday.getYear()
- need not be fully qualified
- document.lastModified
- proceeds from most to least general
- window.document.forms0.inputText1.value
- all names are case sensitive
71Objects ? Object Oriented
- Objects complex data types or containers that
have both data and code - Methods code or functions that work on an
objects properties - Properties data that are stored and retrieved
via object references - This is not true "OO" because the object
hierarchy is not extensible, you can create new
objects, but cannot extend existing ones
72The with Statement
- Establishes the default object for a set of
statements - Within the set of statements, any property
references that do not specify an object are
assumed to be for the default object
73Example of with
- var a, x, y
- var r10
- with (Math) a PI r r x r
cos(PI) y r sin(PI/2) -
74Dynamic HTML
Java Script
Java Script
HTML
CSS
HTML
HTML
CSS
HTML