2 Introduction to JavaScript
Prof. Pranav More
Universal Ai & Future
Technologies School,
Contents
2
Features of JavaScript, Extension of JavaScript,
Syntax of JavaScript: data types, operators, variables, tag,
Document Object Model (DOM) with JavaScript,
Selection Statement using if and Switch,
Iterative statement: for, for/in, while, do while, break and
continue,
Form Validation using JavaScript.
What is JavaScript?
3
JavaScript is Netscape’s cross-platform, object-based
scripting language for client and server applications.
JavaScript is used in millions of Web pages to improve
the design, validate forms, detect browsers, create
cookies, and much more.
JavaScript is the most popular scripting language on the
internet, and works in all major browsers, such as
Internet Explorer, Mozilla, Firefox, Netscape, Opera.
What is JavaScript?
4
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?
5
Client-side: It supplies objects to control a browser and
its Document Object Model (DOM).
Like if client-side extensions allow an application to place
elements on an HTML form and respond to user events
such as mouse clicks, form input, and page
navigation.
Useful libraries for the client-side are AngularJS, ReactJS
and so many others.
What is JavaScript?
6
Server-side: It supplies objects relevant to running
JavaScript on a server.
Like if the server-side extensions allow an application to
communicate with a database, and provide continuity of
information from one invocation to another of the
application, or perform file manipulations on a server.
The useful framework which is the most famous these
days is node.js
Client Side Scripting
7
CS380
Why use client-side
8
programming?
Why also 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
9
programming?
server-side programming 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, ...
How to add JavaScript to
10
HTML
Internal JS: We can add JavaScript directly to our
HTML file by writing the code inside the <script> tag.
The <script> tag can either be placed inside the
<head> or the <body> tag according to the
requirement.
External JS: We can write JavaScript code in other
file having an extension.js and then link this file inside
the <head> tag of the HTML file in which we want to
add this code.
Linking to a JavaScript file:
11
script
<script src="filename" type="text/javascript"></script>
script tag should be placed in HTML
page's head
script code is stored in a separate .js file
JS code can be placed directly in the
HTML file's body or head (like CSS)
but this is bad style (should separate
content, presentation, and behavior
Event-driven programming
12
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
JavaScript Variables
Variables are used to store data.
A variable is a "container" for information
you want to store. A variable's value can
change during the script. You can refer to
a variable by name to see its value or to
change its value.
Rules for variable names:
Variable names are case sensitive
They must begin with a letter or the underscore
character
strname – STRNAME (not same)
JavaScript Operators- 1
Arithmetic Operators Operator
+
Description
Addition
Example
x=2
Result
4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
5/2 2,5
% Modulus (division 5%2 1
remainder)
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
JavaScript Operators – 2
Assignment Operators Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
JavaScript Operators - 3
Comparison Operator
==
Description
is equal to
Example
5==8 returns false
Operators === is equal to (checks for x=5
both value and
type) y="5"
x==y returns true
x===y returns
false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal 5>=8 returns false
to
<= is less than or equal to 5<=8 returns true
JavaScript Operators - 4
Bitwise Operators
JavaScript Operators - 5
Logical Operators
Operator Description Example
&& and x=6
y=3
(x < 10 && y > 1)
returns true
|| or x=6
y=3
(x==5 || y==5)
returns false
! not x=6
y=3
!(x==y) returns
true
JavaScript Operators - 6
Special Operators
Alert Box
20
alert(“This is an alert box");
JS
a JS command that pops up a dialog box
with a message
Confirm Box
21
A confirm box is often used if you want the
user to verify or accept something.
When a confirm box pops up, the user will
have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true.
If the user clicks "Cancel", the box returns
false.
Popup boxes
22
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
Prompt Box
23
A prompt box is often used if you want the user
to input a value before entering a page.
When a prompt box pops up, the user will have
to click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK“, the box returns the input
value. If the user clicks "Cancel“, the box
returns null.
Event-driven programming
24
you are used to programs start with a
main method.
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...
Buttons
25
<button>Click me!</button> HTML
button's text appears inside tag; can
also contain images
To make a responsive button or other UI
control:
1. choose the control (e.g. button) and event
(e.g. mouse 1. click) of interest
2. write a JavaScript function to run when
the event occurs
3. attach the function to the event on the
control
JavaScript functions
26
function name() {
statement ;
statement ;
...
statement ;
} JS
function myFunction() {
alert("Hello!");
alert("How are you?");
} JS
the above could be the contents of
example.js linked to our HTML page
statements placed into functions can be
evaluated in response to user events
JavaScript Events
27
JavaScript applications in the Navigator are largely
event-driven. Events are actions that occur usually
as a result of something the user does. For
example, clicking a button is an event, as is
changing a text field or moving the mouse over a
hyperlink. You can define event handlers, such as
onChange and onClick, to make your script react
to events.
Here’re a few event handler function
onAbort: user aborts the loading
onClick: user clicks on the link
onChange: user changes value of an element
onFocus: user gives input focus to window
Event handlers
28
<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
Document Object Model
29
(DOM)
The document object represents the whole
html document.
When html document is loaded in the browser, it
becomes a document object.
It is the root element that represents the html
document. It has properties and methods.
By the help of document object, we can add
dynamic content to our web page.
Document Object Properties
30
Let's see the properties of document object that
can be accessed and modified by the document
object.
Accessing field value by
document object:
document.form1.name.valu
e
Document Object Model
31
(DOM)
most JS code
manipulates elements
on an HTML page
we can examine
elements' state
e.g. see whether a box
is checked
we can change state
e.g. insert some new
text into a div
we can change styles
DOM element objects
32
Methods of Document
33
Object
Accessing elements:
34
document.getElementById
var name = document.getElementById("id");
JS
<button onclick="changeText();">Click me!</button>
<span id="output">replace me</span>
<input id="textbox" type="text" />
HTML
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
}
JS
Accessing elements:
35
document.getElementById
document.getElementById returns the
DOM object for an element with a given
id
can change the text inside most
elements by setting the innerHTML
property
can change the text in form controls by
setting the value property
Changing element style:
36
element.style
Property or style
Attribute
object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
Preetify
37
function changeText() {
//grab or initialize text here
// font styles added by JS:
text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
text.style.color = "red"; // or pink?
}
JS
38 More Javascript Syntax
Variables
39
var name = expression; JS
var clientName = "Connie Client";
var age = 32;
var weight = 127.4; JS
variables are declared with the var
keyword (case sensitive)
types are not specified, but JS does have
types ("loosely typed")
Number, Boolean, String, Array, Object,
Function, Null, Undefined
can find out a variable's type by calling
typeof
Number type
40
var enrollment = 99;
var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
JS
integers and real numbers are the same
type (no int vs. double)
same operators: + - * / % ++ -- = += -=
*= /= %=
similar precedence to Java
many operators auto-convert types: "2"
* 3 is 6
Comments (same as Java)
41
// 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
Math object
42
var rand1to10 = Math.floor(Math.random() * 10 + 1);
var three = Math.floor(Math.PI);
JS
methods: abs, ceil, cos, floor, log,
max, min, pow, random, round, sin,
sqrt, tan
properties: E, PI
Special values: null and
43
undefined
var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
JS
undefined : has not been declared, does
not exist
null : exists, but was specifically
assigned an empty or null value
Why does JavaScript have both of these?
Logical operators
44
> < >= <= && || ! == != === !==
most logical operators automatically
convert types:
5 < "7" is true
42 == 42.0 is true
"5.0" == 5 is true
=== and !== are strict equality tests;
checks both type and value
"5.0" === 5 is false
if/else statement (same as
45
Java)
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
identical structure to Java's if/else
statement
JavaScript allows almost anything as a
condition
Boolean type
46
var iLike190M = true;
var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS
any value can be used as a Boolean
"falsey" values: 0, 0.0, NaN, "", null, and
undefined
"truthy" values: anything else
converting a value into a Boolean
explicitly:
var boolValue = Boolean(otherValue);
var boolValue = !!(otherValue);
for loop (same as Java)
47
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"
JS
while loops (same as Java)
48
while (condition) {
statements;
} JS
do {
statements;
} while (condition);
JS
break and continue keywords also
behave as in Java
Arrays
49
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS
var ducks = ["Huey", "Dewey", "Louie"];
var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
JS
Array methods
50
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // 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
String type
51
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
JS
methods: charAt, charCodeAt,
fromCharCode, indexOf, lastIndexOf,
replace, split, substring, toLowerCase,
toUpperCase
charAt returns a one-letter String (there is
no char type)
length property (not a method as in Java)
Strings can be specified with "" or ''
More about String
52
escape sequences behave as in Java: \' \"
\& \n \t \\
converting between numbers and
var Strings:
count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah
ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN JS
accessing the letters of a String:
var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work in IE
var lastLetter = s.charAt(s.length - 1);
JS
Splitting strings: split and
53
join
var s = "the quick brown fox";
var a = s.split(" ");
// ["the", "quick", "brown", "fox"]
a.reverse();
// ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
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
JavaScript using Regular
54
Expression
A regular expression is a pattern of
characters.
The pattern is used to do pattern-
matching "search-and-replace" functions
on text.
In JavaScript, a RegExp Object is a pattern
with Properties and Methods.
Regular Expression-
55
Modifiers
Syntax:
/pattern/modifier(s);
Example:
universalai The pattern to search for
/universalai/ A regular expression
/universalai/i A case-insensitive regular
expression
Regular Expression-
56
Methods
Method Description
Executes a search for a match in a string. It returns an array of information
exec()
or null on a mismatch.
test() Tests for a match in a string. It returns true or false.
Returns an array containing all of the matches, including capturing groups,
match()
or null if no match is found.
matchAll() Returns an iterator containing all of the matches, including capturing groups.
Tests for a match in a string. It returns the index of the match, or -1 if the search
search()
fails.
Executes a search for a match in a string, and replaces the matched substring with
replace()
a replacement substring.
Executes a search for all matches in a string, and replaces the matched substrings
replaceAll()
with a replacement substring.
Uses a regular expression or a fixed string to break a string into an array of
split()
substrings.
Regular Expression-
57
Modifiers
Modifiers are used to perform case-insensitive and
global searches:
g- Perform a global match (find all matches
rather than stopping after the first match)
i- Perform case-insensitive matching
m- Perform multiline matching. It only affects the
behavior of start ^ and end $.
^ specifies a match at the start of a string.
$ specifies a match at the end of a string.
Regular Expression- Groups
58
Brackets [abc] specifies matches for the
characters inside the brackets.
Brackets can define single characters, groups, or
character spans:
Examples:
[abc] Any of the characters a, b, or c
[A-Z] Any character from uppercase A to
uppercase Z
[a-z] Any character from lowercase a to lowercase
z
[A-z] Any character from uppercase A to lowercase
Regular Expression- Groups
59
[abc] : Find any character between the brackets
[^abc] : Find any character NOT between the
brackets
[0-9] : Find any character between the brackets (any
digit)
[^0-9] : Find any character NOT between the
Regular Expression-
. 60
Metacharacters
Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word, beginning like this: \bHI, end like this: HI\b
\B Find a match, but not at the beginning/end of a word
\0 Find a NULL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
\udddd Find the Unicode character specified by a hexadecimal number dddd
Regular Expression-
61
Quantifiers
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
N? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
?!n Matches any string that is not followed by a specific string n
62 THANK YOU….!