Title: Lecture 5: Introduction to Javascript I
1Lecture 5 Introduction to Javascript I
- Java and Javascript
- Intro. to Javascript
- Variables operators
- Control Structure
- Functions
- Duration and Scope
21. Java and Javascript
- Java
- A technology for creating active documents called
applets. - Provides high quality animations
- Includes an extensive graphics toolkit consisting
of run-time support for graphics as well as
interface software in the library - Java will NOT be covered in this course since it
will be covered in IEG4180 (3rd year). In this
course, only Javascript will be covered. - JavaScript is an alternative to Java, it
- incorporates a few basic features of Java
- omits many complex features of Java
- can be embedded in a standard HTML file.
- A browser
- Performs the specified computation
- Displays the results
- Offers similar functionality as Java
31. Java and Javascript
- Java
- A compiler is needed to convert Java source
program into bytecode, understood by Java
interpreter - Relatively more complex
- Javascript
- Simplicity ease of use
- Can be interpreted by browser in its source form
- Source representation is less compact than
bytecode representation transporting a source
program takes longer time
41. Java Applets
- Edit
- Use an editor, e.g. emacs, notepad, Jbuilder,
Visual J, to type Java program - File has .java extension
- Compile
- Translates program into bytecodes, understood by
Java interpreter - javac myProgram.java
- Creates .class file containing bytecodes
(myProgram.class) - Embed
- Embed in HTML document using APPLET tag
51. Java Applets
- The applet is embedded in an HTML page by using
the APPLET tag.
62. Introduction to JavaScript
- JavaScript scripting language
- Originally created by Netscape
- Facilitates disciplined approach to designing
computer programs - Enhances functionality and appearance of Web
pages - Jscript
- Microsofts version of JavaScript
72. Introduction to JavaScript
- Browser includes JavaScript Interpreter
- Processes JavaScript commands
- Whitespace
- Blank lines, space characters, tab characters
- Generally ignored by browser
- Used for readability and clarity
- ltSCRIPTgtlt/SCRIPTgt tag
- Encloses entire script
- Attribute LANGUAGE JavaScript
- Indicates scripting language
- Tag must be closed at the end of the script
82. Introduction to JavaScript
- JavaScript is similar to C, C
- case-sensitive
- arithmetic operators , -, , /,
- equality/relational operators , lt, gt
- increment/decrement operators , --
- loosely type language - does not require
variables to have a type before they can be used.
- control structures
- selection if, if/else, switch
- repetition while, do/while, for
- object libraries arrays, math functions
92. Introduction to JavaScript
- A Simple Program Printing a Line of Text in a
Web Page
ltHTMLgt ltHEADgt ltTITLEgt Printing a Line with
Multiple Statements lt/TITLEgt ltSCRIPT LANGUAGE
"JavaScript"gt document.write( "ltFONT
COLOR'magenta'gtltH1gtWelcome to "
) document.writeln( "JavaScript
Programming!lt/H1gtlt/FONTgt" ) lt/SCRIPTgt lt/HEADgt ltB
ODYgtlt/BODYgt lt/HTMLgt
102. Introduction to JavaScript
- Correct method call syntax
- object.method( string, additional arguments
) - e.g. document.writeln( ltH1gtargumentlt/H1gt )
- object document, method writeln
- case-sensitive, like all JavaScript functions
- Prints the string, which can consist of any text
and HTML tags - String must be surrounded by quotation marks
() - Statement terminators
- All statements must end with semi-colons ()
- Scripts restart when page reloaded/refreshed
112.1 JavaScript Variables
- Variables
- Location in memory where values are stored
- Variable name can be any valid identifier
- Identifier series of characters
- Letters, digits, underscores (_) and dollar
signs () - Cannot begin with a digit
- Valid identifiers
- Welcome, value, _value, m_inputField1, C3PO and
R2D2 - Invalid identifiers 7button, Say\Hello and
field5 - Identifiers are case-sensitive
122.1 JavaScript Variables
- JavaScript - loosely typed language
- Does not require variable to have type before use
in program (unlike other languages) - Variable can contain a value of any data type
- JavaScript often converts between values of
different types automatically - When declaring variables
- If not given value, variable has undefined value
- To indicate variable has no value, assign it null
132.1 JavaScript Arithmetic Operators
- Binary Operators
- Used in arithmetic operations
- Modulus operator ()
- Yields remainder after division
- Examples
- 43 5 3
- 8.7 3.4 1.9
- 24 6 0
142.1 JavaScript Operators Precedence
- Arithmetic operations
- Operate right to left (like the sign)
- Rules of operator precedence
- Operations execute in a specific order
152.1 JavaScript Operators
- Assignment operations with identical results can
be written different ways - Example 1
- c c 3
- Example 2
- c 3
- Both ways add 3 to the value of c
- Example 2 executes faster
- Small difference for individual operations
- Significant over large number of operations
162.1 JavaScript Arithmetic Assignment Operators
172.1 JavaScript Increment and Decrement Operators
- Increment operator ()
- Example
- c is identical to c 1 is identical to c
c 1 - Decrement operator (--)
- Example
- c-- is identical to c - 1 is identical to c
c - 1 - Faster operation
- Save time over many repetitions
- Can be preincremented/decremented or
postincremented/decremented - Only makes a difference when variable appears in
context of larger expression
182.1 JavaScript Pre/Post-Increment/Decrement
Operators
- Increment and Decrement Operators
192.1 JavaScript Operators
- Equality and Relational Operators used in
decision making - if structure
- Program makes decision based on truth or falsity
of condition - If condition met (true)
- Statement(s) in body of structure executed
- If condition not met (false)
- Statement(s) in body of structure skipped
202.1 JavaScript Equality and Relational Operators
212.1 JavaScript Logical Operators
- Logical operators
- Used to form more complex conditions by combining
simple conditions - Logical operators are
- (logical AND)
- (logical OR)
- ! (logical NOT or logical negation)
222.2 JavaScript Structured Programming
- Rules for Forming Structured Programs
- Rule 1 Begin with the simplest flowchart
- Rule 2 Any rectangle (action) can be replaced by
two rectangles (actions) in sequence - Rule 3 Any rectangle (action) can be replaced by
any control structure (sequence, if, if/else,
switch, do/while or for) - Rules 2 and 3 may be applied as often as you like
and in any order
232.2 JavaScript Structured Programming
- Repeatedly Applying Rule 2 to the Simplest
Flowchart
242.2 JavaScript Structured Programming
- Applying Rule 3 to the Simplest Flowchart
252.2 JavaScript Control Structures
- Structured approach 7 single-entry/single-exit
pieces - Selection control structures
- if structure (single selection)
- if/else structure (double selection)
- switch structure (multiple selection)
- Repetition control structures
- while structure
- do/while structure
- for structure
- for/in structure
26(No Transcript)
272.2 JavaScript Control Structures
- All control structure names are keywords
- Reserved by language for feature implementation
- May not be used as variable names
282.2 JavaScript Control Structures
- Any form of control in JavaScript can be
expressed through - if structure (selection)
- while structure (repetition)
- Control structures combined in two ways
- Control-structure stacking
- Single-entry/single-exit structures
- Control-structure nesting
- Program readability
- Indent statements in body of each control
structure - Blank line before and after each major control
structure - Avoid more than three levels of nesting
292.2 JavaScript If/Else Selection Structure
- Flowchart
- JavaScript statement
- if ( grade gt 60 )
- document.writeln( Passed )
- else
- document.writeln( Failed )
302.2 JavaScript If/Else Selection Structure
- JavaScript interpreter
- Associates else statement with previous if
statement unless indicated otherwise by braces
() - Example
- if ( x gt 5 )
- if ( y gt 5 )
- document.writeln( x and y are gt 5 )
- else
- document.writeln( x is lt 5 )
- Because of indent, appears that else statement
applies to first if statement - But in fact, it is applied to the second if
statement
312.2 JavaScript If/Else Selection Structure
- To have JavaScript interpret the structure
correctly, utilize braces () - if ( x gt 5 )
- if ( y gt 5 )
- document.writeln( x and y are gt 5 )
-
- else
- document.writeln( x is lt 5 )
- else statement now applies to first if statement
322.2 Switch structure
ltheadgt lttitlegtSwitching between XHTML List
Formatslt/titlegt ltscript type "text/javascript"gt
var choice, // users
choice startTag, // starting list item
tag endTag, // ending list item
tag validInput true, // indicates if input is
valid listType // list type as a
string choice window.prompt( "Select a list
style\n" "1 (bullet), 2 (numbered), 3
(lettered)", "1" )
332.2 Switch structure
switch ( choice ) case "1" startTag
"ltulgt" endTag "lt/ulgt" listType
"lth1gtBullet Listlt/h1gt" break case
"2" startTag "ltolgt" endTag
"lt/olgt" listType "lth1gtOrdered List
Numberedlt/h1gt" break case "3" startTag
"ltol type \"A\"gt" endTag
"lt/olgt" listType "lth1gtOrdered List
Letteredlt/h1gt" break default validInput
false
342.2 Switch structure
if ( validInput true )
document.writeln( listType startTag )
for ( var i 1 i lt 3 i
) document.writeln( "ltligtList item " i
"lt/ligt" ) document.writeln( endTag
) else document.writeln( "Invalid
choice " choice ) // --gt lt/scriptgt lt/HEADgt
35 2.2 Switch structureProgram Output
362.2 Switch structure Program Output
379.5 switch Multiple-Selection Structure
. . .
Fig. 9.8 switch multiple-selection structure.
382.2 JavaScript While Repetition Structure
- Counter-controlled repetition requires
- 1. Name of control variable (or loop counter)
- 2. Initial Value of control variable
- 3. Increment (or decrement) of control variable
per loop - 4. Condition that tests for final value of
control variable - Equivalent Structures
- for structure
- for ( initialization loopContinuationTest
increment ) - statement
- while structure
- initialization
- while ( loopContinuationTest )
- statement
- increment
-
392.2 JavaScript While Repetition Structure
- Example Printing a text with increasing font
size. - Flowchart
402.2 JavaScript While Repetition Structure
ltHTMLgt ltHEADgt ltTITLEgt Counter-Controlled
Repetition lt/TITLEgt ltSCRIPT LANGUAGE
"JavaScript"gt var counter 1 //
initialization while ( counter lt 7 ) //
repetition condition document.writeln(
"ltPgtltFONT SIZE '" counter "'gtHTML font
size " counter "lt/FONTgtlt/Pgt" ) counter
// increment lt/SCRIPTgt lt/HEADgt ltBOD
Ygtlt/BODYgt lt/HTMLgt
412.2 JavaScript While Repetition Structure
422.2 JavaScript Do/While Repetition Structure
ltHTMLgt ltHEADgt ltTITLEgt Counter-Controlled
Repetition lt/TITLEgt ltSCRIPT LANGUAGE
"JavaScript"gt var counter 1 do
document.writeln( "lth" counter "gtThis is "
"an h" counter " level head" "lt/h"
counter "gt" )
counter while ( counter lt 6
) lt/SCRIPTgt lt/HEADgt ltBODYgtlt/BODYgt lt/HTMLgt
432.2 JavaScript Do/While Repetition Structure
442.2 Alter Flow
- The break and continue Statements
- Alter flow of control
- break
- Exits structure
- continue
- Skips remaining statements in structure
continues with next loop iteration - When used properly
- Performs faster than the corresponding structured
techniques
452.2 For Repetition Structure and Break
- Example of break statement
ltHTMLgt ltHEADgt ltTITLEgt Using the break Statement
in a for Structure lt/TITLEgt ltSCRIPT LANGUAGE
"JavaScript"gt for ( var count 1 count lt 10
count ) if ( count 5 ) break //
break loop only if count 5 document.writeln(
"Count is " count "ltBRgt" ) document.writ
eln( "Broke out of loop at count " count
) lt/SCRIPTgt lt/HEADgt ltBODYgtlt/BODYgt lt/HTMLgt
462.2 For Repetition Structure and Break
472.2 For Repetition Structure and Continue
- Example of continue statement
ltHTMLgt ltHEADgt ltTITLEgt Using the continue
Statement in a for Structure lt/TITLEgt ltSCRIPT
LANGUAGE "JavaScript"gt for ( var count 1
count lt 10 count ) if ( count 5
) continue // skip remaining code in loop
only if count 5 document.writeln( "Count is
" count "ltBRgt" ) document.writeln( "Used
continue to skip printing 5") lt/SCRIPTgt lt/HEADgt
ltBODYgtlt/BODYgt lt/HTMLgt
482.2 For Repetition Structure and Continue
492.3 Program Modules in JavaScript
- functions JavaScript modules
- JavaScript programs written by combining
- Functions programmer writes
- prepackaged functions and objects in JavaScript
- These functions often called methods
- Implies function belongs to particular object
- JavaScript provides several rich objects for
performing - Common mathematical operations
- String manipulation
- Date and time manipulation
- Manipulations of arrays
502.3 Program Modules in JavaScript
- Programmer-defined functions
- Written by programmer to define specific tasks
- Statements defining functions written once
- Statements are hidden from other functions
- Function is invoked by a function call
- Specifies function name
- Provides information (or arguments) function
needs for execution - Function call syntax
- functionName( argument )
512.3 Program Modules in JavaScript
- Functions allow program modularization
- Variables declared in function are local
variables - Only known inside function in which defined
- Most functions have list of parameters
- Means for communicating info between functions
function calls - Local variables
- When function called, arguments assigned to
parameters in function definition
522.3 Program Modules in JavaScript
- Motives for modularizing a program with functions
- Makes program development more manageable
- Allows software reusability
- Programs can be created from standard functions
instead of being built from customized code - Example parseInt(), parseFloat
- Functions should be limited to performing a
single, well-defined task - Avoid repeating code in program
- Do not re-invent the wheel
- Save time
532.3 Function Definitions
- Function-definition format
- function function-name ( parameter-list )
-
- Declarations and Statements
-
- Function name - any valid identifier
- Parameter list - comma-separated list containing
names of parameters received by the function when
it is called - If function does not receive values,
parameter-list is left empty
542.3 Function Definitions
- Function body or block
- declarations and statements within braces
- Control
- Returned to the point at which function was
called - If function does not return a result
- When right-brace is reached return statement is
executed - If function returns a result
- When return expression is executed
- Returns value of expressions to caller
- One argument in function call for each parameter
in function definition
552.3 Function Definitions
- Example of function definitions to calculate the
square of a number
ltHTMLgt ltHEADgt ltTITLEgt A Programmer-Defined square
Function lt/TITLEgt ltSCRIPT LANGUAGE
"JavaScript"gt document.writeln("ltH1gtSquare the
numbers from 1 to 10lt/H1gt" ) // square the
numbers from 1 to 10 for ( var x 1 x lt 10
x ) document.writeln( "The square of " x
" is " square( x ) "ltBRgt" ) // The
following square function's body is executed only
// when the function is explicitly called.
// square function definition function
square( y ) return y y lt/SCRIPTgt lt/H
EADgt ltBODYgtlt/BODYgt lt/HTMLgt
562.3 Function Definitions
572.4 Identifier Duration and Scope
- Each identifier has duration and scope
- Duration (or lifetime) is the period during which
identifier exists in memory. - Some identifiers exist briefly
- Some identifiers are repeatedly created and
destroyed - Some identifiers exist for entire execution of
the program - Identifiers which represent local variables in a
function have automatic duration - Automatically created when program control enters
function - Exist while function is active
- Automatically destroyed when function is exited
- Referred to as local variables
582.4 Identifier Duration and Scope
- JavaScript also has identifiers of static
duration - Typically defined in ltHEADgt section of HTML
document - Exist from point at which declared until browsing
session over - Referred to as global variables or script-level
variables
592.4 Identifier Duration and Scope
- Scope of identifier is portion of program in
which identifier can be referenced - Local variable declared in a function can be used
only in that function - Identifiers declared inside a function have
function (or local) scope - Begins with opening brace () of function
- Ends with closing brace() of function
- Function parameters also have local scope
- If local variable has same name as global
variable, global variable is hidden from body of
function
602.4 Identifier Duration and Scope
- Example demonstrating the scoping issues with
global variables and local variables.
ltHTMLgt ltHEADgt ltTITLEgt A Scoping Example
lt/TITLEgt ltSCRIPT LANGUAGE "JavaScript"gt var x
1 // global variable function start()
var x 5 // variable local to function
start document.writeln( "local x in start is "
x ) functionA() // functionA has local
x functionB() // functionB uses global
variable x functionA() // functionA
reinitializes local x functionB() // global
variable x retains its value document.writeln(
"ltPgtlocal x in start is " x "lt/Pgt" )
612.4 Identifier Duration and Scope
function functionA() var x 25 //
initialized each time function A is
called document.writeln( "ltPgtlocal x in
functionA is " x " after entering
functionA" ) x document.writeln(
"ltBRgtlocal x in functionA is " x " before
exiting functionAlt/Pgt" ) function
functionB() document.writeln( "ltPgtglobal
variable x is " x " on entering functionB"
) x 10 document.writeln( "ltBRgtglobal
variable x is " x " on exiting
functionBlt/Pgt" ) lt/SCRIPTgt lt/HEADgt ltBODY
ONLOAD "start()"gtlt/BODYgt lt/HTMLgt
622.4 Identifier Duration and Scope
632.4. JavaScript Predefined (or Global) Functions
642.4. JavaScript Predefined (or Global) Functions
65Further Readings
- Note This topic is designed with the objective
of providing an introduction to Javascript. - Advanced features of Javascript are beyond the
scope of this course and will NOT be taught or
discussed. Students who wish to invest more time
on studying advanced features and topics of
Javascript are referred to the following
resources - Deitel Chapter 7-10
- http//developer.netscape.com/docs/manuals/javascr
ipt.html