Basics of Javascript: Unit-3
Basics of Javascript: Unit-3
Prepared by,
Prepared by,
Divya
Divya
Asst. Prof. ISE dept.
Asst. Prof. ISE dept.
VCET, Puttur
Overview of Javascript,
Overview of Javascript,
Object orientation & Javascript,
Object orientation & Javascript,
Syntactic characteristics,
Syntactic characteristics,
Primitives, operations,
Primitives, operations,
&epressions
&epressions
,
,
Screen o!tp!t and "eyboard inp!t,
Screen o!tp!t and "eyboard inp!t,
#ontro$ statements,
#ontro$ statements,
Object creation and modification,
Object creation and modification,
%rrays,
%rrays,
!nctions,
!nctions,
#onstr!ctors,
#onstr!ctors,
Pattern matchin'
Pattern matchin'
!sin' re'!$ar epressions,
!sin' re'!$ar epressions,
(rrors in scripts,
(rrors in scripts,
1
1
.
.
O
O
V
V
E
E
R
R
V
V
I
I
E
E
W
W
O
O
F
F
JA
JA
V
V
ASCRIPT
ASCRIPT
Ori'ins
Ori'ins
The official name of the standard language
The official name of the standard language is ECAScript.
is ECAScript.
!avaScript can "e divided into three parts#
!avaScript can "e divided into three parts#
▪
▪
the core, client side, and server side.
the core, client side, and server side.
▪
▪
The
The
core
core
is the heart of the language, including its operators,
is the heart of the language, including its operators,
e$pressions, statements, and su"programs.
e$pressions, statements, and su"programs.
▪
▪
#$ient-side JavaScript
#$ient-side JavaScript
is a collection of o"%ects that support
is a collection of o"%ects that support
the control of a "ro&ser and interactions &ith users.
the control of a "ro&ser and interactions &ith users.
▪
▪
Server-side
Server-
side JavaScript
JavaScript
is a collection of o"%ects that ma'e the
is a collection of o"%ects that ma'e the
language useful on a (e" server.
language useful on a (e" server.
OVERVIEW OF
OVERVIEW OF
JA
OVERVIEW OF
OVERVIEW OF
JA
JA
V
V
ASCRIPT
ASCRIPT
Uses Of Javascript
Uses Of Javascript
!avaScript is implemented at ) ends#
!avaScript is implemented at ) ends#
Client end
Client end *
* is em"e
is em"edded in
dded in +T-
+T- documents
documents
Server end
Server end
!avaScript support D /Document "%ect odel0 &hich ena"les
!avaScript support D /Document "%ect odel0 &hich ena"les
!avaScript to access and modify CSS properties and content of any
!avaScript to access and modify CSS properties and content of any
element of a
OVERVIEW OF
OVERVIEW OF
JA
JA
V
V
ASCRIPT
ASCRIPT
(vent-driven #omp!tation Of Javascript
(vent-driven #omp!tation Of Javascript
supports user interactions
supports user interactions through the
through the +T- f
+T- form elements
orm elements
on the client display
on the client display
to chec' the values provided in forms "y users
to chec' the values provided in forms "y users
perform input chec's at the client side
perform input chec's at the client side itself &hich saves "oth
itself &hich saves "oth
server time and internet time.
server time and internet time.
OVERVIEW OF
OVERVIEW OF
JA
JA
V
V
ASCRIPT
ASCRIPT
Brows
Browsers %nd *htm$+Javascript
ers %nd *htm$+Javascript oc!ments
oc!ments
(hen a !avaScript script is encountered in the document, the "ro&ser(hen a !avaScript script is encountered in the document, the "ro&ser uses its
)
)
OBJ(#
OBJ(#
. O/0(1
. O/0(1.
.
%
%
.
.0O1 %
0O1 %
1 J%
1 J%
2
2
%
%
S#/0P.
S#/0P.
:
:
•
•
!avaScript is an o"%ect*"ased language
!avaScript is an o"%ect*"ased language
••
Does
Does not have
not have classes*
classes* no clas
no class*"ased
s*"ased inheritance
inheritance
••
!avaScript cannot support polymorphism.
!avaScript cannot support polymorphism.
•JAVASCRIPT OBJECTS
JAVASCRIPT OBJECTS
"%ects are collections of properties"%ects are collections of properties
Each property is either a data property or a Each property is either a data property or a function or method property.function or method property.
Data properties #Data properties #
primitive values and references to other o"%ects primitive values and references to other o"%ects
!avaScript uses non*o"%ect types for some of its simplest types3 these non*!avaScript uses non*o"%ect types for some of its simplest types3 these non*
o"%ect types #
o"%ect types # primitives. primitives.
"%ects are varia"les too."%ects are varia"les too.
var car 6 78iat73
var car 6 78iat73
The o"%ects are &ritten as name#value pairs The o"%ects are &ritten as name#value pairs
var car 6 9type#78iat7, model#:;;,
var car 6 9type#78iat7, model#:;;, color#7&hite7<3color#7&hite7<3
The name # values pairs =in !avaScript o"%ects> are calledThe name # values pairs =in !avaScript o"%ects> are called
properties
properties
.."%ect Properties
"%ect Properties Accessing : Accessing :
objectName.propertyName
objectName.propertyName
Object ethods
Object ethods
ethods are stored in properties asethods are stored in properties as
f!nction definitions
f!nction definitions
..objectName.methodName()
3)
3)
4(
4(
1(
1(/%
/%5
5
S6
S61.
1.
%
%
#.
#.0# #7%
0# #7%
/%
/%#.
#.
(/
(/0S.
0S.
0#
0#S
S
0n$ine 8embedded9 JavaScript code:
0n$ine 8embedded9 JavaScript code:
?input type67"utton7 id67hello7 value67ello7
?input type67"utton7 id67hello7 value67ello7 onClic' 6 7&indo&.alert=@onClic' 6 7&indo&.alert=@elloello (orld@>7B
(orld@>7B
0nterna$ JavaScript code:
0nterna$ JavaScript code:
?script
?script language67!avaScript7Blanguage67!avaScript7B ?** hide from the older "ro&sers
?** hide from the older "ro&sers /The actual script commands0 **B stop/The actual script commands0 **B stop hiding
hiding ?scriptB ?scriptB
(terna$ JavaScript code:
(terna$ JavaScript code:
Comments# or .
Comments# or .
Identifiersnames, must "egin &ith a
Identifiersnames, must "egin &ith a letter, an underscore
letter, an underscore
= F >, or a dollar sign =G>.
= F >, or a dollar sign =G>.
)
)
P/
P/
00
00
.02
.02
(S,
(S,
OP(
OP(
/%
/%
.
.
0O1
0O1
S,
S,
%
%
1 (
1 (
*P/
*P/
(SS
(SS
0O1
0O1
S
S
;)
;)
primitive types
primitive types
.. !avaScript has five primitive types# 4um"er, String, 5oolean, Hndefined, !avaScript has five primitive types# 4um"er, String, 5oolean, Hndefined, andand
4ull. 4ull.
.
. !avaScript includes predefined o"%ects!avaScript includes predefined o"%ects
E#
E#
1!mber, Strin', Boo$ean etc
1!mber, Strin', Boo$ean etc
var $ 6 false3 var $ 6 false3 5oolean=$>3 5oolean=$>3
var y 6 ne& String=7!ohn7>3 var y 6 ne& String=7!ohn7>3
)
)
1!
1!
me
meri
ric
c
%
%
nd St
nd
Stri
ri
n'
n'
5i
5ite
te
ra
ra$s
$s
All numeric literals are values of
All numeric literals are values of type 4um"er.type 4um"er.
0nte'er $itera$s0nte'er $itera$s #Integer literals are strings of digits. #Integer literals are strings of digits. var
var $ $ 6 6 ;$883 ;$883 $ $ &ill &ill "e "e ):: ):: he$adecimalhe$adecimal
$oatin'-point $itera$s$oatin'-point $itera$s
var y 6 J)Ke*:3 var y 6 J)Ke*:3
strin' $itera$strin' $itera$
<6
<6oo!=>r!=>re the most $e the most $ove$y persove$y person 0=>ve eveon 0=>ve ever metr met‟‟
<:==boo"fi$es? <:==boo"fi$es? ---
3) O.7(/ P/00.02( .6P(S :
3) O.7(/ P/00.02( .6P(S :
1!$$ :1!$$ : UndefinedUndefined var p6null3 var p6null3 var pJ3 var pJ3 alert=p> null alert=p> null alert=pJ> undefined alert=pJ> undefined Boo$eanBoo$ean)
)
(
(
#5
#5
%/
%/
01
01
4 2
4 2
%
%
/0
/0
%B
%B
5(
5(
S
S
A
A varia"le that h
varia"le that has "een declared
as "een declared "ut
"ut
not assigned a value, has the value
not assigned a value, has the value
undefined.
undefined.
@)
A
A
)
)
.
.
7
7
(
(
a
a
t
t
h O
h O
B
B
J
J
(
(
#
#
.
.
ath.ma$=;, J:;, K;, );, *L>
ath.ma$=;, J:;, K;, );, *L>
ath.round=:.K>3 :
ath.round=:.K>3 :
ath.sMrt=N>3
ath.sMrt=N>3
(r
(r
ite %s program to accept
ite %s program to accept
K num"ers using prompt and
K num"ers using prompt and
find the largest
find the largest
of three using alert method.
of three using alert method.
Hse predefined function ath.ma$.
Hse predefined function ath.ma$.
7
?htmlB
?htmlB
?headB?script language67!avaScript7B
?headB?script language67!avaScript7B
?**
?**
function sM=>
function sM=>
9
9
va
va
r a6
r a6
pr
pr
om
om
pt= 7
pt= 7
Ent
Ent
er f
er f
irs
irs
t nu
t nu
m"
m"
er 7 , 7
er 7 , 7
7 >3
7 >3
a6parseInt=a>3
a6parseInt=a>3
var "6prompt= 7Enter first num"er 7 , 77 >3
var "6prompt= 7Enter first num"er 7 , 77 >3
"6parseInt=">3
"6parseInt=">3
var c6prompt= 7Enter first num"er 7 , 77 >3
var c6prompt= 7Enter first num"er 7 , 77 >3
"6parseInt=">3
"6parseInt=">3
var ma$6ath.ma$=a,",c>3
var ma$6ath.ma$=a,",c>3
alert=7largest of three input num"er#7Oma$>3
alert=7largest of three input num"er#7Oma$>3
< **B
< **B
?scriptB?headB
?scriptB?headB
?"odyB?formB?input type67"utton7 value67sM7 onclic'67sM=>37B
?"odyB?formB?input type67"utton7 value67sM7 onclic'67sM=>37B
?formB
?formB
?"odyB
?htmlB?headB ?htmlB?headB ?script language67!avaScript7B ?script language67!avaScript7B ?** ?**
var val 6 4um"er.A+FVA-HE3
var val 6 4um"er.A+FVA-HE3
var smallest4um 6 4um"er.I4FVA-HE3
var smallest4um 6 4um"er.I4FVA-HE3
var infinite4um 6
var infinite4um 6 4um"er.4um"er.PSITIVEFI48I4IT3PSITIVEFI48I4IT3
var negInfinite4um 6 4um"er.4EATIVEFI48I4IT3
var negInfinite4um 6 4um"er.4EATIVEFI48I4IT3
document.&rite =7Value of 4um"er.A+FVA-HE # 7 O val O7?"r B7>3
document.&rite =7Value of 4um"er.A+FVA-HE # 7 O val O7?"r B7>3
document.&rite =7Va
document.&rite =7Value of lue of smallest4um # 7 smallest4um # 7 O smallest4umO7?"r B7 O smallest4umO7?"r B7 >3>3
document.&rite =7Va
document.&rite =7Value of lue of infinite4um # 7 infinite4um # 7 O infinite4um O7?"r O infinite4um O7?"r B7>3B7>3
document.&rite =7Va
document.&rite =7Value of lue of negInfinite4um # 7 negInfinite4um # 7 O negInfinite4um O7?"r O negInfinite4um O7?"r B7>3B7>3
var dayfonth6)KJ3 var dayfonth6)KJ3 if =dayfonth ? J QQ dayfonth B KJ> if =dayfonth ? J QQ dayfonth B KJ> 9 9 dayfonth
dayfonth 6 6 4um"er.4um"er.4a44a4
alert=7Day
alert=7Day of of onth onth must must "e "e "et&een "et&een J J and and KJ.7>KJ.7>
< < **B **B ?scriptB?headB?"odyB?"odyB?htmlB ?scriptB?headB?"odyB?"odyB?htmlB
)
)
.h
.h
e St
e St
ri
ri
n' #
n' #
at
at
en
en
at
at
io
io
n Op
n Op
er
er
at
at
or
or
: C
: C
E$ampleJ#
E$ampleJ#
<%!'!st ? C
<%!'!st
? C ;DEE
;DEE ++
++ <%!'!st
<%!'!st ;DDE?
;DDE?
(amp$e:
(amp$e: E
E F
F <3?
<3? ++
++ ;
;
.o strin' conversion :
.o strin' conversion :
String constructor string=> ,
String constructor string=> ,
toStrin'89
toStrin'89
The glo"al method
The glo"al method
1!mber89
1!mber89 can convert strings to num"ers.
can convert strings to num"ers.
The parseInt=> function parses a string and returns an integer.
The parseInt=> function parses a string and returns an integer.
var
var e
e 6
6 parseInt=7R;7>
parseInt=7R;7> R;
R;
var g 6 parseInt=7e &as ;7> 4A4
var g 6 parseInt=7e &as ;7> 4A4
The parse8loat=> function parses a string and returns a floating
The parse8loat=> function parses a string and returns a floating
point num"er
point num"er..
var
var c
c 6
6 parse8loat=7J;.KK7>
parse8loat=7J;.KK7> J;.KK
J;.KK
parse8loat=7e &as ;7> 4
parse8loat=7e &as ;7> 4A4
A4
;G)
;G)
(p
(p
$ic
$ic
it .
it .
yp
yp
e #o
e #o
nve
nve
rsi
rsi
ons
ons
:
:
N.
;;
;;
)
)
Strin' Properties %
Strin' Properties %
nd ethods
nd ethods
var str 6
var str 6 1eorge231eorge23 var
var str 6
var str 6 1eorge23
1eorge23
str.
str.charAt=
charAt=)>
)> is
is 1o
1o
‟‟
st
strr..in
inde
de$
$f=
f=1r
1r > is
‟‟> is K
K
st
strr..su"
su"st
strin
ring=
g=),
), > is 1
> is 1or
org
g
‟‟
;)
;)
.7( typeo
.7( typeof OP(/%
f OP(/%
.
.
O/
O/
The typeof operator returns the type of its single operandThe typeof operator returns the type of its single operand
ttyyppeeoof 7f 7%%oohhnn2 2 ssttrriinngg V
Vaar r $3 $3 typeof=$typeof=$> undef> undefinedined
;3)
;3)
%ssi'nment Statements
%ssi'nment Statements
.
.
a O6 3 means the same as a 6 a O 3
a O6 3 means the same as a 6 a O 3
var $ 6 J;3
var $ 6 J;3
$
$ 6
6 :3
:3
)
)
;)
;)
.7( ate OBJ(#. :
.7( ate OBJ(#. :
var today = new Date()
var today = new Date()
@)
@)
S#
S#
/(
/((1
(1
OU
OU.P
.PU.
U.
%
%
1
1
H(
H(6B
6B
O%
O%/
/
01
01PU
PU.
.
?htmlB?headB?sc
?htmlB?headB?script ript language67!avaScript7Blanguage67!avaScript7B ?**
?**
function my8unction=> 9 function my8unction=> 9
a$ert
a$ert
=7ello I am an alert "o$7>3=7ello I am an alert "o$7>3 varvar person person 66
prompt
prompt
=7Please enter your name7, 7arry Potter7>3=7Please enter your name7, 7arry Potter7>3 ifif =person =person 6 6 null> null> 99
doc!ment)write
doc!ment)write
=person>3 <=person>3 <confirm
confirm
=7Do you &ant to continue this do&nloadU7>3=7Do you &ant to continue this do&nloadU7>3 < < **B **B ?scriptB?headB ?scriptB?headB?"odyB?formB?"utton onclic'67my8unction=>7BTry it?"uttonB ?"odyB?formB?"utton onclic'67my8unction=>7BTry it?"uttonB ?formB?"odyB?htmlB
A
A
ta"le of num"ers from :*J: and
ta"le of num"ers from :*J: and
their sMuares , cu"es using alert
their sMuares , cu"es using alert
The Muadratic eMuation is given "y#
The Muadratic eMuation is given "y#
ax
ax
))O
O
bx
bx
O
O
c
c
6 ;
6 ;
The e$pression inside the sMuare root is called
The e$pression inside the sMuare root is called
discriminant
discriminant
and is
and is
denoted "y #
denoted "y #
▪
▪
6
6
b
b
))*
*
ac
ac
(hen
(hen
B;, there are ) real
B;, there are ) real
roots
roots
▪
#reate an *7.5
#reate an *7.5
and JavaScript
and JavaScript to comp!te
to comp!te the
the
rea$ r
A
A
)
)
#
#
O
O
1
1
.
.
/
/
O
O
5
5
S
S
.
.
%
%
.
.
(
(
(
(
1
1
.
.
S :
S :
;
;
)
)
#
#
o
o
n
n
tr
tr
o
o
$ (
$ (
pr
pr
e
e
ss
ss
i
i
o
o
n
n
s :
s :
Welational operators
Welational operators
) Se$ection Statements
) Se$ection Statements
Wr!te a "ava#r!$t #ode%
Wr!te a "ava#r!$t #ode%
To 'nd revere o a *!ven n+,-er.
To 'nd revere o a *!ven n+,-er.
..\web_exercises
..\web_exercises
\chapter4_js\4.14reverse.html
\chapter4_js\4.14reverse.html
e ! and !/e0
e ! and
!/e0e tate,ent to #e#2
e tate,ent to #e#2
n+,-er ! $r!,e or not
n+,-er ! $r!,e or not
..\..\web_lab\
..\..\web_lab\
js\prime_wrong.html
js\prime_wrong.html
..\..\web_lab\
..\..\web_lab\
js\prime.html
js\prime.html
466J not prim
466J not prim
e
e
466) prime
466) prime
8or=$6)3 $?n3$OO>
8or=$6)3 $?n3$OO>
9If=nX$66;>
9If=nX$66;>
Weturn not prime
Weturn not prime
<
<
Else
Else
prime
prime
3)
3)
w!t#
w!t#
Statements
Statements
?htmlB?headB?sc
?htmlB?headB?script ript language67!avaScript7Blanguage67!avaScript7B ?**
?**
var "s6prompt=7 select "order siYe7>3 var "s6prompt=7 select "order siYe7>3 s&itch="s> 9
s&itch="s> 9
case 7J7# document.&rite=7?ta"leB7>3 "rea'3 case 7J7# document.&rite=7?ta"leB7>3 "rea'3
case 7)7# document.&rite=7?ta"le "order6@J@B7>3 "rea'3 case 7)7# document.&rite=7?ta"le "order6@J@B7>3 "rea'3 Case 7K7# document.&rite=7?ta"le "order6@L@B7>3 "rea'3 Case 7K7# document.&rite=7?ta"le "order6@L@B7>3 "rea'3 default# document.&rite=7invalid choice7>3"rea'3
default# document.&rite=7invalid choice7>3"rea'3 < < document.&rite=7?captionBta"leJ?captionB7>3 document.&rite=7?captionBta"leJ?captionB7>3 document.&rite=7?trB?thBA?thB?thB5?thB7>3 document.&rite=7?trB?thBA?thB?thB5?thB7>3 document.&rite=7?trB?tdBa?tdB?tdB"?tdB?ta"leB7>3 document.&rite=7?trB?tdBa?tdB?tdB"?tdB?ta"leB7>3 **B **B ?scriptB?headB?"odyB?"odyB?htmlB ?scriptB?headB?"odyB?"odyB?htmlB
)
)
5OO
5OO
P S.
P S.
%
%
.((1.S
.((1.S
whi$e
whi$e
for and do-whi$e
for and do-whi$e
;)
;) Usi
Usin' d
n' doc!
oc!men
ment)w
t)writ
rite89,
e89, wr
write
ite cod
code th
e that d
at disp
isp$ays
$ays the
the
res!$ts of the ; times tab$e) 0ts
res!$ts of the ; times tab$e) 0ts o!tp!t sho!$d be the
o!tp!t sho!$d be the
res!$ts of the ca$c!$ations)
res!$ts of the ca$c!$ations)
))=))=webM$ab=js=;Mtab$es)htm$
))=))=webM$ab=js=;Mtab$es)htm$
)
) .
.o
o pr
prin
int f
t fac
acto
tori
ria$
a$ of
of a n
a n!m
!mbe
berr
..Z..Z&e"Fla"Z
E)
E)
OBJ
OBJ(#.
(#.
#/
#/(%
(%
.
.
0O1
0O1
%
%
1
1 O
O
00#
00#%
%
.
.0O1
0O1
new
new
operator creates a "lan' o"%ect# no properties.
operator creates a "lan' o"%ect# no properties.
constructor
constructor
var myMobject I new Object89N
var myMobject I new Object89N
The varia"le
The varia"le
myMobject
myMobject
references the ne& o"%ect
references the ne& o"%ect
var myMcar I ma"e: <ord?,
var myMcar I ma"e: <ord?, mode$: <#onto!r S2.?N
mode$: <#onto!r S2.?N
Properties can be accessed in two ways)
Properties can be accessed in two ways)
var prop; I myMcar)ma"eN
var prop; I myMcar)ma"eN
var prop I myMcarQ<ma"e?RN
var prop I myMcarQ<ma"e?RN
the varia"les propJ and prop) "oth have the value U.
the varia"les propJ and prop) "oth have the value U.
The num"er of properties in a !avaScript o"%ect is dynamic
The num"er of properties in a !avaScript o"%ect is dynamic
de$ete myMcar)mode$N
de$ete myMcar)mode$N
loop statement, for*in, for listing the properties of an o"%ect.
loop statement, for*in, for listing the properties of an o"%ect.
for =var a in
for =var a in
myMcar 9
myMcar 9
document.&rite=14ame#2, a, 1value#2 myFcar/a0>3
document.&rite=14ame#2, a, 1value#2 myFcar/a0>3
3
3
.
.
A
A
R
R
R
R
A
A
4
4
S
S
;)
;)
%rray OBJ(#. #/(%.0O1
%rray OBJ(#. #/(%.0O1
a.
a.
Var a6ne& Array=J, ), 2three2>3
Var a6ne& Array=J, ), 2three2>3
V
Vaar "6
r "6ne& Array=J;
ne& Array=J;;>3
;>3
".
".
var myFlistF) 6 /J, ), 1three2,
var myFlistF) 6 /J, ), 1three2, 1four203
1four203
)
)
#7%/%#.(/0S.0#S O %rray OBJ(#.S
#7%/%#.(/0S.0#S O %rray OBJ(#.S
aQER I N
aQER I N
the new $en'th of myM$ist wi$$ be
the new $en'th of myM$ist wi$$ be
$en'th property:
%rray eamp$e:
%rray eamp$e:
.his scr
.his scr
ipt has an array o
ipt has an array o
f names, which
f names, which
are in
are in
a$phabetica$ order)
a$phabetica$ order)
0t !ses prompt to 'et new
0t !ses prompt to 'et new
names, one at
names, one at
a time,
a time,
and inserts them into the eistin' array
and inserts them into the eistin' array
?htmlB?headB?scrip
?htmlB?headB?script t language67!avaScriplanguage67!avaScript7Bt7B ?**
?** var
var nameFlist nameFlist 6 n6 ne& e& Array=7"Array=7"a"y7, a"y7, 1c*man7, 1c*man7, 7[asper1, 7[asper1, 7ichael7, 7ichael7, 7Wo"erto7>37Wo"erto7>3 var
var ne&Fname, ne&Fname, inde$, inde$, last3last3 &hile =ne&Fname
&hile =ne&Fname 6 6 prompt=7Pprompt=7Please type a ne& lease type a ne& name7, 77>> 9name7, 77>> 9 last 6 nameFlist.length * J3
last 6 nameFlist.length * J3
&hile =last B6 ; \\ nameFlist/last0 B ne&Fname> 9 &hile =last B6 ; \\ nameFlist/last0 B ne&Fname> 9
nameFlist/last O J0 6 nameFlist/last03 nameFlist/last O J0 6 nameFlist/last03 last**3 last**3 < < nameFlist/l
nameFlist/last O J0 ast O J0 6 ne&Fname36 ne&Fname3 document.&rite=
document.&rite=7?pB?"BThe ne& name 7?pB?"BThe ne& name list is#?"B 1, 7?"r B7>3list is#?"B 1, 7?"r B7>3 for
for =inde$ =inde$ 6 6 ;3 ;3 inde$ inde$ ? ? nameFlist.lengnameFlist.length3 th3 inde$OO>inde$OO> document.&rite=n
document.&rite=nameFlist/indameFlist/inde$0, e$0, 7?"r 7?"r B7>3B7>3 document.&rite=7?pB7>3 document.&rite=7?pB7>3 < < **B **B ?scriptB?headB?"odyB?"odyB?htmlB ?scriptB?headB?"odyB?"odyB?htmlB
3
3
)
)
%
%
r
r
r
r
a
a
y
y
e
e
t
t
h
h
o
o
d
d
s
s
Join ethod
Join ethod
/everse ethod T
/everse ethod T
no parameter no parameter
Sort ethod T
Sort ethod T
arrange*no parameter arrange*no parameter
#oncat ethod:
#oncat ethod:
to the end of the Array o"%ectto the end of the Array o"%ect
S$ice ethod :
S$ice ethod :
returns and Rreturns and R
toStrin' method:
toStrin' method:
These strings are catenated, separated "y These strings are catenated, separated "y commas.commas.
p!sh, pop, !nshift, and shift methods
p!sh, pop, !nshift, and shift methods
shift and !nshift methods
shift and !nshift methods
var deer I $ist)shift89N ++ deer is
var deer I $ist)shift89N ++ deer is now <asher?
now <asher?
$ist)!nshift8<asher?9N ++ .his p!ts <asher? bac" on
$ist)!nshift8<asher?9N ++ .his p!ts <asher? bac" on $ist
$ist
.
.
o find n!mber of eros, ne'atives and positives
o find n!mber of eros, ne'atives and positives
in a
in a
'iven array !sin' switch statement
'iven array !sin' switch statement
..\web_exercises
..\web_exercises
\chapter4_js\4.11_array_switch.html
U1#.0O1S
U1#.0O1S
/et!rn
/et!rn
statement# returns control statement# returns control to the to the function caller.function caller...
ne or more return statements in function "odyne or more return statements in function "ody
function fun=> function fun=> 9 9 Alert=1hi2> Alert=1hi2> < < no return
no return
or
or
=doesnot include any e$pression> is =doesnot include any e$pression> is!ndefined
!ndefined
5O#%
5O#%
5 2
5 2
%
%
/0%
/0%
B5(S
B5(S
The scope of a varia"le is the range
The scope of a varia"le is the range of statements over &hich it is visi"le.of statements over &hich it is visi"le. used only &ithin a function ***have local scope
used only &ithin a function ***have local scope
'$oba$ variab$e scopeV
'$oba$ variab$e scopeV
they are visi"le in the entire +T- document.they are visi"le in the entire +T- document.
P%/%(.(/S
P%/%(.(/S
))=))=Web 1otes by ivya )pdf
))=))=Web 1otes by ivya )pdf
The parameter values that appear in a call to a function are called
The parameter values that appear in a call to a function are called
actual parameters.
actual parameters.
The parameter names in calls to the function, are called formal
The parameter names in calls to the function, are called formal
parameters.
parameters.
!avaScript uses the pass*"y*value parameter*passing method.
!avaScript uses the pass*"y*value parameter*passing method.
In the function, e$cess actual parameters that are passed are
In the function, e$cess actual parameters that are passed are
ignored3
ignored3
e$cess formal parameters are set to undefined.
e$cess formal parameters are set to undefined.
ar'!ments)$en'th -
ar'!ments)$en'th -
can determine the num"er of actual
can determine the num"er of actual
parameters that &er
D
D
U
U
1#
1#
.0
.0
O1
O1
S :
S :
So
So
rt
rt
e
e
th
th
od
od
, /
, /
ev
ev
is
is
it
it
ed
ed
?htmlB ?htmlB ?headB ?headB ?script language67!avaScript7B ?script language67!avaScript7B ?** ?** var
var letters letters 6 6 /7Ws7,7s7,78s7,7-s703/7Ws7,7s7,78s7,7-s703 var num"ers 6 /)L,:,K03 var num"ers 6 /)L,:,K03 letters.sort=>3 letters.sort=>3 num"ers .sort=>3 num"ers .sort=>3 alert=letters>3 alert=letters>3 alert=num"ers >3 alert=num"ers >3
n!mbers
n!mbers
)sort8f!nction
)sort8f!nction
n!mberMsort8a,
n!mberMsort8a,
b9
b9
ret!rn
ret!rn
a
a
-
-
bN
bN
9N
9N
alert=num"ers
alert=num"ers >3 >3 ascendingascending **B
**B
?scriptB?headB?"odyB?"odyB?htmlB ?scriptB?headB?"odyB?"odyB?htmlB
;G edian of an array:
;G edian of an array:
?htmlB?headB?sc
?htmlB?headB?script ript language67!avaScript7B ?**language67!avaScript7B ?** function median=list> 9
function median=list> 9
$ist)sort8f!nction 8a, b9 ret!rn a - bN9N
$ist)sort8f!nction 8a, b9 ret!rn a - bN9N
v
vaar r lliissttFFlleen n 6 6 lliisstt..lleennggtthh33
A
A
or or ifif ==listFlen ==listFlen X X )> )> 66 66 J> J>
G
G
or or JJ returnreturn list/ath.floor=listFlen list/ath.floor=listFlen )>03)>03 else
else
return ath.round==list/listFlen ) * J0 O list/listFlen )0> )>3
return ath.round==list/listFlen ) * J0 O list/listFlen )0> )>3
++even
++even
< < var myFlistFJ 6 /L, K, N, J, , 03 var myFlistFJ 6 /L, K, N, J, , 03 var myFlistF) 6 /J;, *), ;, :, K, J, 03 var myFlistF) 6 /J;, *), ;, :, K, J, 03var med I median8myM$istM;9N
var med I median8myM$istM;9N
document.&rite=7edian
document.&rite=7edian of /of /7, my7, myFlistFJ, FlistFJ, 70 70 is# is# 7, 7, med, med, 7?"r 7?"r B7>3B7>3
med I median8myM$istM9N
med I median8myM$istM9N
document.&rite=7edian
document.&rite=7edian of of /7, /7, myFlistF), myFlistF), 70 70 is# is# 1, 1, med, med, 7?"r 7?"r B7>3B7>3 **B?scriptB?headB?"odyB?"odyB?htmlB **B?scriptB?headB?"odyB?"odyB?htmlB
ath)f$oor8;)A9N
++;
ath)f$oor8;)A9N
++;
ath)ro!nd8;)A9
++
ath)ro!nd8;)A9
++
i> T
i> To print the position in the
o print the position in the string of
string of the leftmost
the leftmost
vo&el.
vo&el.
..Z&e"Fe$ercisesZchapterF%sZ.J;Fvo&el.html
..5we-6e7er#!e
..5we-6e7er#!e
5#a$ter86"58.36re,ove69ero
5#a$ter86"58.36re,ove69ero
.t,0
.t,0
;)
;)
4iven array m!st be mo
4iven array m!st be mo
dified to remove a$$ ero va$!es)
dified to remove a$$ ero va$!es)
.
.
The splice=> method
The splice=> method addsremoves items tofrom an ar
addsremoves items tofrom an array,
ray, and
and
returns the removed item=s>.
returns the removed item=s>.
arr.splice=
arr.splice=i
i
,, J
J
>3
>3
Index
Index
# A
# An integer that specifies at
n integer that specifies at &hat position to
&hat position to
addremove items
addremove items
howmany
howmany
. The num"er of items to "e
. The num"er of items to "e removed. If set to ;,
removed. If set to ;,
no items &ill "e removed
no items &ill "e removed
0np!t: %
0np!t: %
rray of
rray of
n!mbers
n!mbers
O!tp!t: avera'e of each rows of matri
O!tp!t: avera'e of each rows of matri
..Z&e"Fe$ercisesZchapterF%sZ.JKFmatri$.html
..Z&e"Fe$ercisesZchapterF%sZ.JKFmatri$.html
;)
;)
inp!t yo!r sentence
inp!t yo!r sentence
)
)
Sort based on !ser inp!t8ascendin' or descendin'9
Sort based on
!ser inp!t8ascendin' or descendin'9
J.
J. The split=> method is used to split a string into an array ofThe split=> method is used to split a string into an array of su"strings, and returns the ne&
su"strings, and returns the ne& array.array.
).
;;)
;;)
0n JavaScript, a$most Xeverythin'X is an object)
0n JavaScript, a$most Xeverythin'X is an object)
5ooleans, Strings ,4um"ers can "e o"%ects =or primitive data treated as5ooleans, Strings ,4um"ers can "e o"%ects =or primitive data treated as
o"%ects> o"%ects>
Dates are al&ays o"%ectsDates are al&ays o"%ects
aths are al&ays o"%ectsaths are al&ays o"%ects
Arrays are al&ays o"%ectsArrays are al&ays o"%ects
8unctions are al&ays o"%ects....8unctions are al&ays o"%ects....
Objects are variab$
Objects are variab$
es too) B!t objects can
es too) B!t objects can
contain many va$!es)
contain many va$!es)
var person 6 7!ohn Doe73var person 6 7!ohn Doe73
var person 6 9first4ame#7!ohn7, last4ame#7Doe7, age#:;, eyeColor#7"lue7<3 var person 6 9first4ame#7!ohn7, last4ame#7Doe7, age#:;, eyeColor#7"lue7<3
var person 6 ne& "%ect=>3
var person 6 ne& "%ect=>3
person.first4am
person.first4ame 6 7!ohn73
e 6 7!ohn73
person.last4ame 6 7Doe73
person.last4ame 6 7Doe73
person.age 6 :;3
person.age 6 :;3
person.eyeColor 6 7"lue73
person.eyeColor 6 7"lue73
;;)
;;)
(
(ith !avaScript, you can define and
ith !avaScript, you can define and create your o&n
create your o&n o"%ects.
o"%ects.
create and initialiYe the properties of ne&ly created o"%ects.
create and initialiYe the properties of ne&ly created o"%ects.
(hen the constructor is called,
(hen the constructor is called,
this
this
is a reference to the ne&ly
is a reference to the ne&ly
created o"%ect.
created o"%ect.
The
The
this
this
varia"le is used to construct and initialiYe the
varia"le is used to construct and initialiYe the
properties of the o"%ect.
properties of the o"%ect.
?htmlB?headB?script language67!avaScript7B ?**
?htmlB?headB?script language67!avaScript7B ?**
var my8ather 6 ne& person=7!ohn7, 7Doe7, :;, 7"lue7>3
var my8ather 6 ne& person=7!ohn7, 7Doe7, :;, 7"lue7>3
var myother 6 ne& person=7Sally7, 7Wally7, L, 7green7>3
var myother 6 ne& person=7Sally7, 7Wally7, L, 7green7>3
my8ather.display=>3
my8ather.display=>3
myother.display=>3
myother.display=>3
function person=first, last, age, eye> 9
function person=first, last, age, eye> 9
this.first4ame
this.first4ame
6
6
first3
first3
this.last4ame
this.last4ame
6
6
last3
last3
this.age
this.age
6
6
age3
age3
this.eyeColor
this.eyeColor
6
6
eye3
eye3
this.display6display3
this.display6display3
<
<
function display=>9
function display=>9
document.&rite=7father is 7 O this.age O 7. mother is 7 O
document.&rite=7father is 7 O this.age O 7. mother is 7 O
this.first4ameO7?"rB7>3
this.first4ameO7?"rB7>3
<
<
**B
**B
?scriptB?headB?"odyB?"odyB?htmlB
?scriptB?headB?"odyB?"odyB?htmlB
;
;
P%
P%
..(/1
..(/1 %.
%.
#70
#7014
14 B6
B6 US0
US014
14
/(4U5%/ (*P/(SS0O1S
/(4U5%/ (*P/(SS0O1S
approaches:
approaches:
WegE$p
WegE$p
String o"%ect
String o"%ect
search method
search method returns the position in the String o"%ect
returns the position in the String o"%ect
=through &hich it is called> at &hich the pattern matched
=through &hich it is called> at &hich the pattern matched
The position of the first character in the string is ;.
The position of the first character in the string is ;.
If there is no match, search returns ]J.
If there is no match, search returns ]J.
Var str61hi hello23
Var str61hi hello23
V
#7%/%#.(/
#7%/%#.(/
%1 #7%/%#.(/
%1 #7%/%#.(/
-#5%SS
-#5%SS
P%
P%
..(/1S
..(/1S
etacharacters are characters that have special meanings in some conte$ts in etacharacters are characters that have special meanings in some conte$ts in
patterns. patterns.
.he fo$$owin' are the pattern metacharacters:
.he fo$$owin' are the pattern metacharacters:
= Y 8 9 Q R Z [ F C )
= Y 8 9 Q R Z [ F C )
etacharacters can themselves "e matched "y "eing immediately precededetacharacters can themselves "e matched "y "eing immediately preceded
"y a "ac'slash. "y a "ac'slash.
A period matches any character e$cept ne&line.A period matches any character e$cept ne&line.
E$ample#
E$ample#
+snow)
+snow)+ matches <snowy?, <
+ matches <snowy?, <snowe?, and <snowd?
snowe?, and <snowd?
E$ample#E$ample#
+3=)+ matches 3))
+3=)+ matches 3))
but /3.4/ would match 3.4 and 374, amongbut /3.4/ would match 3.4 and 374, among others.others.
E$ample#
E$ample#
QabcR matches \a> , \b> & \c>
QabcR matches \a> , \b> & \c>
E$ample#E$ample#
Qa-hR matches
Qa-hR matches any $
any $owercase $etter from \a> to \h>
owercase $etter from \a> to \h>
E$ample#
^pearl
^pearl
Pattern odifiers
Pattern odifiers
TheThe
i modifier
i modifier
ma'es the letters in the pattern match either upperma'es the letters in the pattern match either uppercasecaseor lo&ercase letters in the string. or lo&ercase letters in the string. Applei
Applei matches matches _APP-E`, _APP-E`, _apple`, _apple`, _APPle`,_APPle`,
TheThe
modifier
modifier
allo&s &hite space to appear in the pattern. allo&s &hite space to appear in the pattern.OTHER PTTERN!"T#H$N% "ETHO&' O( 'tr)ng OTHER PTTERN!"T#H$N% "ETHO&' O( 'tr)ng
var str I <red, reddie, and rederica were sib$in's?N
var str I <red, reddie, and rederica were sib$in's?N
str)rep$ace8+re+', <Boy?9N
str)rep$ace8+re+', <Boy?9N
atches returns array /, K0. atches returns array /, K0.
var str I <
^Z&O
^Z&O
/Z.*0U
/Z.*0U
=/Z.*0UZ&O>
=/Z.*0UZ&O>
Simp$e re'!$ar epression to va$idate emai$ address
Simp$e re'!$ar epression to va$idate emai$ address
personalFinfodomain
personalFinfodomain
.he persona$Minfo part c
.he persona$Minfo part contains the fo$$owin' %S#00 characters)
ontains the fo$$owin' %S#00 characters)
Hppercase =A*b> and lo&ercase =a*Y> English letters.Hppercase =A*b> and lo&ercase =a*Y> English letters.
Digits =;*N>.Digits =;*N>.
Characters G X \ @ O * 6 U ^ F 9 Q < Characters G X \ @ O * 6 U ^ F 9 Q <
Character . = period, dot or Character . = period, dot or fullstop> provided that it is not the first orfullstop> provided that it is not the first or
last character and it &ill not come one after the other. last character and it &ill not come one after the other.
domain name
domain name /for e$ample com, org, net, in, us, info0 part contains
/for e$ample com, org, net, in, us, info0 part containsletters, digits, hyphens and dots. letters, digits, hyphens and dots.
mysite]o!rearth)com
mysite]o!rearth)com
my)ownsite]o!rearth)or'
my)ownsite]o!rearth)or'
mysite]yo!)me)net
mysite]yo!)me)net
var reg 6^Z&O=/Z.*0UZ&O>
var reg 6^Z&O=/Z.*0UZ&O>
]
]
Z&O=/Z.*0UZ&O>=Z.Z&9),K<>OG3Z&O=/Z.*0UZ&O>=Z.Z&9),K<>OG3=)=w,3---=)=w,3---
It matches a . follo&ed "y t&o or three &ord characters,It matches a . follo&ed "y t&o or three &ord characters, e.g., .edu, .org, .com, .u', .us, .co etc.JK
JK
J.
J.
(r
(r
ite a !avascript that
ite a !avascript that
contains, a function
contains, a function
named
named
testM
testM
phonenoMn!m
phonenoMn!m
, &hich tests the phone num"er of the format ddd ]
, &hich tests the phone num"er of the format ddd ]
dddd ?;NJ * L):RB and display &hether the given num"er is valid
dddd ?;NJ * L):RB and display &hether the given num"er is valid
or not using document.&rite.
or not using document.&rite.
).
).
..Z..Z&e"Fla"Z%sZphoneFnumFvalidate.html
..Z..Z&e"Fla"Z%sZphoneFnumFvalidate.html
K.
K.
(r
(rite a !avaScript to
ite a !avaScript to validate the name, the n
validate the name, the name should "e
ame should "e
entered using prompt. The first and last name should
entered using prompt. The first and last name should not "e more
not "e more
than J; characters and middle name must contain only initial. If
than J; characters and middle name must contain only initial. If
so display validation co
so display validation corresponding name. The format is the
rresponding name. The format is the
firstFname, secondFname and thirdFname. There should "e single
firstFname, secondFname and thirdFname. There should "e single
&hite space "et&een 8irstFname, SecondFname and thirdFname.
&hite space "et&een 8irstFname, SecondFname and thirdFname.
; (//O/S 01 S#/0P.S
S$ot te error..
S$ot te error..
var userAge 6 prompt=1Please enter your age2>3
var userAge 6 prompt=1Please enter your age2>3
if =userAge 6 ;>3
if =userAge 6 ;>3
9
9
alert=1So you`re a "a"y2>3
alert=1So you`re a "a"y2>3
<
<
else if = userAge ? ; Q userAge B );;>
else if = userAge ? ; Q userAge B );;>
alert=
alert=1I thin' you
1I thin' you may "e lying
may "e lying a"out your age2>3
a"out your age2>3
else
else
9
9
alert=1That`s a good age2>3
alert=1That`s a good age2>3
<
ERRORS I: SCRIPTS
(rite +T- document and %ava script code to
(rite +T- document and %ava script code to
impleme
implement the
nt the follo&ing #
follo&ing #
i>
i>
To count the num"er of names in the given array
To count the num"er of names in the given array
that end in either 7ie7 or 7y7.
that end in either 7ie7 or 7y7.
ii>
.r!e if the strin' has the form:
.r!e if the strin' has the form:
strin';, strin' $etter
strin';, strin' $etter
strin';, strin'---m!st be $owercase ecept the first $etter
strin';, strin'---m!st be $owercase ecept the first $etter
$etter-$etter-
---m!st
---m!st
be !ppercase
be !ppercase