Module -2 Introduction to JavaScript
Why use client-side programming?
2
Why use client-side scripting?
◻ client-side scripting (JavaScript) benefits:
? usability: can modify a page without having to post
back to the server (faster UI)
? efficiency: can make small, quick changes to page
without waiting for server
? event-driven: can respond to user actions like clicks and
key presses
Why use client-side programming?
3
◻ server-side programming (PHP) benefits:
? security: has access to server's private data; client can't
see source code
? compatibility: not subject to browser compatibility
issues
? power: can write files, open connections to servers,
connect to databases, ...
What is JavaScript?
4
What is JavaScript?
5
◻ a lightweight programming language ("scripting
language")
? used to make web pages interactive
? insert dynamic text into HTML (ex: user name)
? react to events (ex: page load user click)
? get information about a user's computer (ex: browser
type)
? perform calculations on user's computer (ex: form
validation)
What is JavaScript?
6
Client Side Scripting
7
Where did JavaScript fits in?
8
What can JavaScript Do?
9
Uses of JavaScript
10
◻ Use it to add multimedia elements
With JavaScript you can show, hide, change, resize images, and
create image rollovers. You can create scrolling text across the
status bar.
◻ Create pages dynamically
Based on the user's choices, the date, or other external data,
JavaScript can produce pages that are customized to the user.
◻ Interact with the user
It can do some processing of forms and can validate user input
when the user submits the form.
JavaScript v/s Java
11
◻ interpreted, not compiled
◻ more relaxed syntax and rules
? fewer and "looser" data types
? variables don't need to be declared
? errors often silent (few exceptions)
◻ key construct is the function rather than the class
? "first-class" functions are used in many situations
◻ contained within a web page and integrates with its
HTML/CSS content
JavaScript v/s Java
12
JavaScript Syntax
13
JavaScript Syntax
14
<script src="filename" type="text/javascript"></script>
HTML
Writing JavaScript
15
Example
16
<html>
<body>
<script type="text/javascript">
[Link]("Hello World!");
</script>
</body>
</html>
Where to put your Script?
17
Implementing JavaScript
18
External scripts
19
Example:
20
<html>
<body>
<script type=“text/javascript”>
[Link](“ JavaScript is case sensitive”);
//[Link](“ <h1><b>JavaScript is case
sensitive</b></h1>”);
</script>
</body>
</html>
JavaScript Variables
21
◻ Variables can be thought of as named containers. You can
place data into these containers and then refer to the data
simply by naming the container.
◻ Before you use a variable in a JavaScript program, you must
declare it. Variables are declared with the var keyword
◻ To assign values to variables, add an equal sign and the value:
let userName = "Smith"
let price = 100
JavaScript Variables Scope
22
◻ The scope of a variable is the region of your
program in which it is defined. JavaScript variable
will have only two scopes.
• Global Variables (var): A global variable has
global scope which means it is defined everywhere
in your JavaScript code.
• Local Variables(let): A local variable will be visible
only within a function where it is defined. Function
parameters are always local to that function.
JavaScript Variable Names Rules
23
◻ You should not use any of the JavaScript reserved keyword as
variable name. These keywords are mentioned in the next
section. For example, break or boolean variable names are
not valid.
◻ JavaScript variable names should not start with a numeral
(0-9). They must begin with a letter or the underscore
character. For example, 123test is an invalid variable name
but _123test is a valid one.
◻ JavaScript variable names are case sensitive. For example,
Name and name are two different variables.
JavaScript Reserved Words
24
JavaScript Operators
25
JavaScript Constructs
26
◻ if, else, while, for, switch, case
JavaScript Constructs
27
JavaScript Functions
28
JavaScript Functions
29
<SCRIPT language = "JavaScript">
function showAlert() {
alert("this is a user-defined function.")
}
</SCRIPT>
<INPUT type-"button" value="Run the Function"
onClick="showAlert()">
JavaScript Comments
30
◻ // single line
◻ /* …. */
JavaScript Popup boxes
31
◻ Alert Dialog Box:
JavaScript Popup boxes
32
◻ Confirmation Dialog Box:
◻ A confirmation dialog box is mostly used to take user's consent
on any option. It displays a dialog box with two buttons: OK
and Cancel. You can use confirmation dialog box as follows:
JavaScript Popup boxes
33
JavaScript Popup boxes
34
◻ Prompt Dialog Box:
Comments in JavaScript
35
// single-line comment
/* multi-line comment */
JS
◻ identical to Java's comment syntax
◻ recall: 4 comment syntaxes
? HTML: <!-- comment -->
? CSS/JS/PHP: /* comment */
? Java/JS/PHP: // comment
? PHP: # comment
JavaScript Arrays
36
JavaScript has arrays that are indexed starting at 0
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS
var ducks = ["Huey", "Dewey", "Louie"];
var stooges = []; // [Link] is 0
stooges[0] = "Larry"; // [Link] is 1
stooges[1] = "Moe"; // [Link] is 2
stooges[4] = "Curly"; // [Link] is 5
stooges[4] = "Shemp"; // [Link] is 5
JS
37
Special version of for works with arrays
JavaScript Arrays
38
var a = ["Stef", "Jason"]; // Stef, Jason
[Link]("Brian"); // Stef, Jason, Brian
[Link]("Kelly"); // Kelly, Stef, Jason, Brian
[Link](); // Kelly, Stef, Jason
[Link](); // Stef, Jason
[Link](); // Jason, Stef
JS
◻ array serves as many data structures: list, queue,
stack, ...
◻ methods: concat, join, pop, push, reverse, shift,
slice, sort, splice, toString, unshift
push and pop add / remove from back
unshift and shift add / remove from front
shift and pop return the element that is removed
JavaScript Errors
39
◻ There are three types of errors in programming:
(a) Syntax Errors
Syntax errors, also called parsing errors, occur at compile
time for traditional programming languages and at interpret
time for JavaScript.
JavaScript Errors
40
(b) Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
(c) Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors
are not the result of a syntax or runtime error. Instead, they occur when you
make a mistake in the logic that drives your script and you do not get the result
you expected.
JavaScript Exception Handling
41
◻ JavaScript implements the try...catch...finally
construct as well as the throw operator to handle
exceptions.
◻ You can catch programmer-generated and runtime
exceptions, but you cannot catch JavaScript syntax
errors.
JavaScript Exception Handling
42
43
JavaScript Form Validation
44
◻ Form validation used to occur at the server, after
the client had entered all necessary data and then
pressed the Submit button.
◻ If some of the data that had been entered by the
client had been in the wrong form or was simply
missing, the server would have to send all the data
back to the client and request that the form be
resubmitted with correct information.
◻ This was really a lengthy process and over
burdening server.
JavaScript Form Validation
45
◻ JavaScript, provides a way to validate form's data
on the client's computer before sending it to the web
server. Form validation generally performs two
functions.
1. Basic Validation - First of all, the form must be checked to
make sure data was entered into each form field that
required it. This would need just loop through each field in
the form and check for data.
2. Data Format Validation - Secondly, the data that is entered
must be checked for correct form and value. This would need
to put more logic to test correctness of data.
JavaScript Form Validation (string fx)
46
JavaScript Events
47
◻ Events are actions that can be detected by
JavaScript.
◻ Examples of events:
• A mouse click
• A web page or an image loading
• Mousing over a hot spot on the web page
• Selecting an input field in an HTML form
• Submitting an HTML form
• A keystroke
Events
48
◻ onLoad and onUnload
◻ onFocus, onBlur and onChange
◻ onSubmit etc
JavaScript Form Validation(RegEx)
49
JavaScript Regular Expressions
50
/[a-zA-Z_\-]+@(([a-zA-Z_\-])+\.)+[a-zA-Z]{2,4}/
◻ A regular expression is a certain way to describe a pattern of
characters.
◻ Pattern-matching or keyword search.
◻ Regular expressions are frequently used to test whether or not a
string entered in an HTML form has a certain format.
◻ A regular expression can be a single character, or a more
complicated pattern.
◻ Regular expressions can be used to perform all types of text
search and text replace operations.
JS Regular Expressions Syntax
51
/pattern/modifiers;
◻ JavaScript provides regular expression capabilities through instances of
the built-in RegExp object.
var regTest = new RegExp (pattern, modifiers);
◻ Pattern specifies the patter of an expression (to be used in a search)
◻ Modifiers specify if a search should be global, case-sensitive .
RegEx Pattern /Modifier
52
Basic regexes
53
/abc/
◻ a regular expression literal in JS is written
/pattern/
◻ the simplest regexes simply match a given substring
◻ the above regex matches any line containing "abc"
? YES : "abc", "abcdef", "defabc",
".=.abc.=."
? NO : "fedcba", "ab c", "AbC", "Bash", ...
Wildcards and anchors
54
. (a dot) matches any character except \n
? /.oo.y/ matches "Doocy", "goofy", "LooPy", ...
? use \. to literally match a dot . character
^ matches the beginning of a line; $ the end
? /^if$/ matches lines that consist entirely of if
\< demands that pattern is the beginning of a word;
\> demands that pattern is the end of a word
? /\<for\>/ matches lines that contain the word
"for"
String match
55
[Link](regex)
◻ if string fits pattern, returns matching text; else null
? can be used as a Boolean true/false test:
if ([Link](/[a-z]+/)) { ... }
◻ g after regex for array of global matches
? "obama".match(/.a/g) returns ["ba", "ma"]
◻ i after regex for case-insensitive match
? [Link](/Marty/i) matches "marty", "MaRtY"
String replace
56
[Link](regex, "text")
◻ replaces first occurrence of pattern with the given text
? var state = "Mississippi";
[Link](/s/, "x") returns "Mixsissippi"
◻ g after regex to replace all occurrences
? [Link](/s/g, "x") returns "Mixxixxippi"
◻ returns the modified string as its result; must be stored
? state = [Link](/s/g, "x");
Special characters
57
| means OR
? /abc|def|g/ matches lines with "abc", "def", or "g"
? precedence: ^Subject|Date: vs. ^(Subject|Date):
() are for grouping
? /(Homer|Marge) Simpson/ matches lines containing
"Homer Simpson" or "Marge Simpson"
\ starts an escape sequence
? many characters must be escaped: / \ $ . [ ] ( ) ^ * + ?
? "\.\\n" matches lines containing ".\n"
Quantifiers: * + ?
58
* means 0 or more occurrences
? /abc*/ matches "ab", "abc", "abcc", "abccc", ...
? /a(bc)/" matches "a", "abc", "abcbc", "abcbcbc", ...
? /a.*a/ matches "aa", "aba", "a8qa", "a!?_a", ...
+ means 1 or more occurrences
? /a(bc)+/ matches "abc", "abcbc", "abcbcbc", ...
? /Goo+gle/ matches "Google", "Gooogle", "Goooogle", ...
? means 0 or 1 occurrences
? /Martina?/ matches lines with "Martin" or "Martina"
? /Dan(iel)?/ matches lines with "Dan" or "Daniel"
More quantifiers
59
{min,max} means between min and max
occurrences
? /a(bc){2,4}/ matches lines that contain
"abcbc", "abcbcbc", or "abcbcbcbc"
◻ min or max may be omitted to specify any number
? {2,} 2 or more
? {,6} up to 6
? {3} exactly 3
Character sets
60
[ ] group characters into a character set;
will match any single character from the set
? /[bcd]art/ matches lines with "bart", "cart", and
"dart"
? equivalent to /(b|c|d)art/ but shorter
◻ inside [], most modifier keys act as normal
characters
? /what[.!*?]*/ matches "what", "what.", "what!",
"what?**!", ...
? Eg : Match letter grades e.g. A+, B-, D.
Character ranges
61
◻ inside a character set, specify a range of chars with -
? /[a-z]/ matches any lowercase letter
? /[a-zA-Z0-9]/ matches any letter or digit
◻ an initial ^ inside a character set negates it
? /[^abcd]/ matches any character but a, b, c, or d
◻ inside a character set, - must be escaped to be matched
? /[\-+]?[0-9]+/ matches optional - or +, followed by at least one
digit
■ Eg : Match phone numbers, e.g. 206-685-2181 .
Built-in character ranges
62
◻ \b word boundary (e.g. spaces between words)
◻ \B non-word boundary
◻ \d any digit; equivalent to [0-9]
◻ \D any non-digit; equivalent to [^0-9]
◻ \s any whitespace character; [ \f\n\r\t\v...]
◻ \s any non-whitespace character
◻ \w any word character; [A-Za-z0-9_]
◻ \W any non-word character
◻ \xhh, \uhhhh the given hex/Unicode character
? /\w+\s+\w+/ matches two space-separated words
63
Event-driven programming
64
◻ split breaks apart a string into an array using a
delimiter
can also be used with regular expressions (seen later)
◻ join merges an array into a single string, placing a
delimiter between them
Event-driven Programming
65
◻ you are used to programs start with a main method
(or implicit main like in PHP)
◻ JavaScript programs instead wait for user actions
called events and respond to them
◻ event-driven programming: writing programs driven
by user events
◻ Let's write a page with a clickable button that pops
up a "Hello, World" window...
Event handlers
66
<element attributes onclick="function();">...
HTML
<button onclick="myFunction();">Click me!</button>
HTML
◻ JavaScript functions can be set as event handlers
? when you interact with the element, the function will execute
◻ onclick is just one of many event HTML attributes we'll
use
◻ but popping up an alert window is disruptive and
annoying
? A better user experience would be to have the message
appear on the page...
67