Vous êtes sur la page 1sur 18

JavaScript Tutorial

1. Introduction 2. Embedding JavaScript into an HTML Document 3. Variable 1. !"at are Variable # 2. Value o$ Variable 3. Data T%pe &onver ion '. Literal 1. Integer 2. (loating)*oint Literal 3. +oolean Literal '. String Literal ,. E caping Literal ,. -rra% .. /perator 1. Selected - ignment /perator 2. &ompari on /perator 3. Selected -rit"metic /perator '. Logical /perator 0. 1 ing JavaScript /b2ect 3. (unction 1. De$ining a (unction 2. &alling a (unction 4. I$5T"en Statement 16. Loop 1. $or Loop 2. 7"ile Loop 11. &ommenting 12. /n)Line Help

1. Introduction
JavaScript i a imple programming language t"at can be 7ritten directl% into HTML document to allo7 $or increa ed interactivit% 7it" t"e u er. (or e8ample9 JavaScript can be u ed to create online calculator or "o7 t"e current date and time.

2. Embedding JavaScript into your HTML document

+ro7 er t"at recogni:e JavaScript al o recogni:e t"e pecial ;S&<I*T= ... ;5S&<I*T= tag. T"i tag goe in t"e ;HE-D= o$ %our HTML document9 along 7it" %our ;TITLE= tag. Here> a "ort e8ample?
<HTML> <HEAD> <TITLE>My JavaScript Page</TITLE> <SCRIPT> (JavaScript code goes i </SCRIPT> </HEAD> (rest o# yo$r HTML doc$%e t goes !ere" !ere"

To ma@e an ob2ect A uc" a an image9 a $orm button9 or a "%perlin@B on %our page do omet"ing in re pon e to a u er action9 %ou can add an additional attribute to t"e tag $or t"at ob2ect. (or e8ample9 t"e $ollo7ing HTML nippet pop up a t"an@ %ou me age 7"en t"e u er clic@ on t"e lin@?
<A HRE&'(!ttp)//***+cs+,ro* +ed$/co$rses/,ridge/( o C-ic.'(a-ert(/T!a .s #or visiti g t!e 0ridge !o%e page1/"(>0ridge !o%e page</A>

Tr% it %our el$C Ju t clic@ on t"e $ollo7ing lin@? +ridge "ome page Dou>re $amiliar 7it" t"e H<E(EFF attribute t"at peci$ie t"e 1<L t"at t"e lin@ point to9 but note t"e additional on&lic@EFF attribute. T"e tu$$ bet7een t"o e Guotation mar@ i JavaScript code9 7"ic" in t"i ca e pop up an alert bo8 7it" t"e peci$ied me age. ADon>t 7orr% i$ %ou don>t under tand t"e tu$$ bet7een t"e Guotation mar@ H %ou>ll learn it later on. T"e important t"ing rig"t no7 i to under tand t"e additional attribute.B -not"er point to recogni:e i t"at i$ a bro7 er doe not under tand t"e ;S&<I*T= tag9 it 7ill @ip over it9 and t"e te8t t"at i bet7een t"e t7o tag A%our code9 ba icall%B 7ill appear on t"e creen a ordinar% te8t. Since %ou 7ant to create an HTML page t"at i vie7able on all bro7 er 9 %ou 7ould 7ant to prevent t"i $rom "appening. To prevent t"i $rom "appening9 %ou "ould include t"e c"aracter ;C)) immediatel% $ollo7ing t"e ;S&<I*T= tag and t"e c"aracter ))= immediatel% preceding t"e ;5S&<I*T= tag. In HTML in general9 u ing t"i et o$ c"aracter allo7 %ou to 7rite comment to %our el$ t"at t"e bro7 er 7ill not read or di pla% on t"e page. In ide t"e JavaScript tag 9 t"e bro7 er ignore t"e e c"aracter . +% doing t"i 9 a non)JavaScript readable bro7 er 7ill ee t"e comment notation and ignore t"e te8t bet7een t"em A7"ic" i %our codeB. Dour code 7ould t"en loo@ li@e t"i ?

<HEAD> <SCRIPT> <122 (3o$r code goes !ere+++" 22> </SCRIPT> </HEAD>

3. Variable
3.1. !"at are Variable #
Variable are li@e torage unit . Dou can create variable to "old value . It i ideal to name a variable omet"ing t"at i logical9 o t"at %ou>ll remember 7"at %ou are u ing it $or. (or e8ample9 i$ %ou 7ere 7riting a program to divide 2 number 9 it could be con$u ing i$ %ou called %our variable number/ne9 numberT7o9 numberT"ree becau e %ou ma% $orget 7"ic" one i t"e divi or9 7"ic" one i t"e dividend9 and 7"ic" one i t"e Guotient. - more logical approac" 7ould be to name t"em 2u t t"at? divi or9 dividend9 Guotient. It i important to @no7 t"e proper %nta8 to 7"ic" variable mu t con$orm?

T"e% mu t tart 7it" a letter or under core AFIFB Sub eGuent c"aracter can al o be digit A6)4B or letter A-)J and5or a):B. <emember9 JavaScript i ca e) en itive. AT"at mean t"at M%Variable and m%Variable are t7o di$$erent name to JavaScript9 becau e t"e% "ave di$$erent capitali:ation.B

Some e8ample o$ legal name are 4$%,er5!its9 te%p669 and 5 a%e. !"en %ou declare a variable b% a ignment out ide o$ a $unction9 it i called a global variable9 becau e it i available ever%7"ere in t"e current document. !"en %ou declare a variable 7it"in a $unction9 it i called a local variable9 becau e it i available onl% 7it"in t"e $unction. 1 ing var i optional9 but %ou need to u e it i$ %ou "ave a variable t"at "a been declared global and %ou 7ant to re)declare it a a local variable in ide a $unction. Variable can tore all @ind o$ data A ee belo79 Value o$ Variable 9 ection 3.2B. To a ign a value to a variable9 %ou u e t"e $ollo7ing notation?
divide d ' 78 divisor ' 98 %yStri g ' (I %ay *a t to $se t!is %essage %$-tip-e ti%es(8 %essage ' %yStri g8

Let> a% t"e main part o$ t"e $unction 7ill be dividing t"e dividend b% t"e divi or and toring t"at number in a variable called :$otie t. I can 7rite t"i line o$ code in m% program? :$otie t ' divisor;divide d9 and I "ave bot" tored t"e value o$ t"e Guotient to t"e variable :$otie t and I "ave declared t"e variable at t"e ame time. I$ I "ad 7anted to9 I could "ave declared it along 7it" m% ot"er a igned variable above9 7it" a value o$ null. -$ter e8ecuting t"e program9 t"e value o$ :$otie t 7ill be 2. It i important to t"in@ about t"e de ign o$ %our program be$ore %ou begin. Dou "ould create t"e appropriate variable o t"at it ma@e %our li$e ea ier 7"en %ou go to 7rite t"e program. (or in tance9 i$ %ou @no7 t"at %ou 7ill be coding a lot o$ t"e ame tring in a me age9 %ou ma% 7ant to create a variable called %essage and give it t"e value o$ %our me age. T"at 7a%9 7"en %ou call it in %our program9 %ou do not "ave to ret%pe t"e ame entence over and over again9 and i$ %ou 7ant to c"ange t"e content o$ t"at me age9 %ou onl% "ave to c"ange it once )) in t"e variable declaration.

3.2. Value o$ Variable


JavaScript recogni:e t"e $ollo7ing t%pe o$ value ?

Kumber 9 uc" a '2 or 3.1'1,4 Logical A+ooleanB value 9 eit"er true or $al e String 9 uc" a FHo7d%CF null9 a pecial @e%7ord 7"ic" re$er to not"ing

T"i relativel% mall et o$ t%pe o$ value 9 or data t%pe 9 enable %ou to per$orm u e$ul $unction 7it" %our application . T"ere i no e8plicit di tinction bet7een integer and real) valued number .

3.3. %ata Type &onver ion


JavaScript i a loo el% t%ped language. T"at mean %ou do not "ave to peci$% t"e data t%pe o$ a variable 7"en %ou declare it9 and data t%pe are converted automaticall% a needed during cript e8ecution. So9 $or e8ample9 %ou could de$ine a variable a $ollo7 ?
var a s*er ' 9<

-nd later9 %ou could a ign t"e ame variable a tring value9 $or e8ample9
a s*er ' (T!a .s #or a-- t!e #is!+++(

+ecau e JavaScript i loo el% t%ped9 t"i a ignment doe not cau e an error me age. Ho7ever9 t"i i not good codingC Dou "ould create variable $or a peci$ic t%pe9 uc" a an integer9 tring9 or arra%9 and be con i tent in t"e value t"at %ou tore in t"e variable. T"i prevent con$u ion 7"en %ou are 7riting %our program.

In e8pre ion involving numeric and tring value 9 JavaScript convert t"e numeric value to tring . (or e8ample9 con ider t"e $ollo7ing tatement ?
= ' (T!e a s*er is ( > 9< y ' 9< > ( is t!e a s*er+(

AT"e L ign tell JavaScript to concatenate9 or tic@ toget"er9 t"e t7o tring . (or e8ample9 i$ %ou 7rite?
%essage ' (He--o( > (?or-d(

...t"en t"e variable %essage become t"e tring (He--o ?or-d(B In t"e $ir t tatement9 8 become t"e tring FT"e an 7er i '2.F In t"e econd9 % become t"e tring F'2 i t"e an 7er.F

'. Literal
Dou u e literal to repre ent value in JavaScript. T"e e are $i8ed value 9 not variable 9 t"at %ou literall% provide in %our cript. E8ample o$ literal include? 123'9 FT"i i a literal9F and tr$e.

'.1. Integer
Integer can be e8pre ed in decimal Aba e 16B9 "e8adecimal Aba e 1.B9 and octal Aba e 3B. - decimal integer literal con i t o$ a eGuence o$ digit 7it"out a leading 6 A:eroB. leading 6 A:eroB on an integer literal indicate it i in octalH a leading 68 Aor 6MB indicate "e8adecimal. He8adecimal integer can include digit A6)4B and t"e letter a)$ and -)(. /ctal integer can include onl% t"e digit 6)0. Some e8ample o$ integer literal are? '29 68(((9 and )3',.

'.2. (loating)point literal


- $loating)point literal can "ave t"e $ollo7ing part ? a decimal integer9 a decimal point AF.FB9 a $raction Aanot"er decimal numberB9 an e8ponent9 and a t%pe u$$i8. T"e e8ponent part i an FeF or FEF $ollo7ed b% an integer9 7"ic" can be igned Apreceded b% FLF or F)FB. - $loating)point literal mu t "ave at lea t one digit9 plu eit"er a decimal point or FeF Aor FEFB. Some e8ample o$ $loating)point literal are 3.1'1,9 )3.1E129 .1e129 and 2E)12

'.3. *oolean literal


T"e +oolean t%pe "a t7o literal value ? true and $al e.

'.'. String literal


- tring literal i :ero or more c"aracter enclo ed in double AFB or ingle A>B Guotation mar@ . - tring mu t be delimited b% Guotation mar@ o$ t"e ame t%peH t"at i 9 eit"er bot" ingle Guotation mar@ or double Guotation mar@ . T"e $ollo7ing are e8ample o$ tring literal ?

Fbla"F >bla"> F123'F Fone line Nn anot"er lineF

In addition to ordinar% c"aracter 9 %ou can al o include pecial c"aracter in tring 9 a "o7n in t"e la t element in t"e preceding li t. T"e $ollo7ing table li t t"e pecial c"aracter t"at %ou can u e in JavaScript tring . &"aracter Meaning Nb bac@ pace N$ $orm $eed Nn ne7 line Nr carriage return Nt tab NN bac@ la " c"aracter

'.+. E caping c"aracter


(or c"aracter not li ted in t"e preceding table9 a preceding bac@ la " i ignored9 7it" t"e e8ception o$ a Guotation mar@ and t"e bac@ la " c"aracter it el$. Dou can in ert Guotation mar@ in ide tring b% preceding t"em 7it" a bac@ la ". T"i i @no7n a e caping t"e Guotation mar@ . (or e8ample9
var :$ote ' (He read @(T!e Cre%atio doc$%e t+*rite(:$ote" o# Sa% McAee@( ,y R+?+ Service+(

T"e re ult o$ t"i 7ould be


He read (T!e Cre%atio o# Sa% McAee( ,y R+?+ Service+

To include a literal bac@ la " in ide a tring9 %ou mu t e cape t"e bac@ la " c"aracter. (or e8ample9 to a ign t"e $ile pat" c?Ntemp to a tring9 u e t"e $ollo7ing?
var !o%e ' (c)@@te%p(

+. ,rray
-n -rra% i an ob2ect 7"ic" tore multiple value and "a variou propertie . !"en %ou declare an arra%9 %ou mu t declare t"e name o$ it9 and t"en "o7 man% value it 7ill need to tore. It i important to reali:e t"at eac" value i tored in one o$ t"e element o$ t"e arra%9 and t"e e element tart at 6. T"i mean t"at t"e $ir t value in t"e arra% i reall% in t"e 6 element9 and t"e econd number i reall% in t"e $ir t element. So $or e8ample9 i$ I 7ant to tore 16 value in m% arra%9 t"e torage element 7ould range $rom 6)4. T"e notation $or declaring an arra% loo@ li@e t"i ?
%yArray ' e* Array(BC"8 #oo ' e* Array(D"8

Initiall%9 all value are et to null. T"e notation $or a igning value to eac" unit 7it"in t"e arra% loo@ li@e t"i ?
%yArrayECF ' DG8 %yArrayEBF ' <H8 %yArrayE6F ' 998

+% putting t"e element number in brac@et O P a$ter t"e arra%> name9 %ou can a ign a value to t"at peci$ic element. Kote t"at t"ere i no uc" element9 in t"i e8ample9 a %yArrayEBCF. <emember9 t"e element begin at %yArrayECF and go up to %yArrayE6F. In JavaScript9 "o7ever9 an arra%> lengt" increa e i$ %ou a ign a value to an element "ig"er t"an t"e current lengt" o$ t"e arra%. T"e $ollo7ing code create an arra% o$ lengt" :ero9 t"en a ign a value to element 44. T"i c"ange t"e lengt" o$ t"e arra% to 166.
co-ors ' e* Array("8 co-orsE66F ' (%id ig!t,-$e(8

+e care$ul to re$erence t"e rig"t cell 9 and ma@e ure to re$erence t"em properl%C +ecau e arra% are ob2ect 9 t"e% "ave certain propertie t"at are pre)de$ined $or %our convenience. (or e8ample9 %ou can $ind out "o7 man% element %yArray "a and tore t"i value in a variable called $%,erI#E-e%e ts b% u ing?
$%,erI#E-e%e ts ' %yArray+-e gt!8

-. .perator

JavaScript "a man% di$$erent operator 9 7"ic" come in everal $lavor 9 including binar%. T"i tutorial 7ill cover ome o$ t"e mo t e ential a ignment9 compari on9 arit"metic and logical operator .

-.1. Selected a ignment operator


-n a ignment operator a ign a value to it le$t operand ba ed on t"e value o$ it rig"t operand. T"e ba ic a ignment operator i eGual AEB9 7"ic" a ign t"e value o$ it rig"t operand to it le$t operand. T"e ot"er operator are "ort"and $or tandard operation . (ind an abridged li t o$ "ort"and operator belo7? S"ort"and operator 8 LE % 8 )E % 8 QE % 8 5E % Meaning 8E8L% 8E8)% 8E8Q% 8E85%

Kote t"at t"e E ign "ere re$er to a ignment9 not FeGual F in t"e mat"ematical en e. So i$ 8 i , and % i 09 = ' = > y i not a valid mat"ematical e8pre ion9 but it 7or@ in JavaScript. It ma@e 8 t"e value o$ 8 L % A12 in t"i ca eB. E/,M0LES1 I$ 8 E 16 and % E 29 8 LE % 7ould mean 8 E 8 L %9 "ence 8> ne7 value 7ould be t"e um o$ 8> previou value plu %> previou value. 1pon e8ecuting 8 E 8 L % E 16 L 29 8> ne7 value become 129 7"ile %> ne7 value remain eGual to it old value. Similarl%9 8 )E % 7ould c"ange 8> value to 3. &alculate 8 QE % and 8 5E % to get a better idea o$ "o7 t"e e operator 7or@.

-.2. &ompari on operator


- compari on operator compare it operand and return a logical value ba ed on 7"et"er t"e compari on i true or not. T"e operand can be numerical or tring value . !"en u ed on tring value 9 t"e compari on are ba ed on t"e tandard le8icograp"ical ordering. T"e% are de cribed in t"e $ollo7ing table. /perator De cription Evaluate to true i$ t"e operand are EGual AE EB eGual. Evaluate to true i$ t"e operand are Kot eGual ACEB not eGual. Evaluate to true i$ le$t operand i Rreater t"an A=B greater t"an rig"t operand. Rreater t"an or Evaluate to true i$ le$t operand i eGual A=EB greater t"an or eGual to rig"t E8ample 8 EE % evaluate to true i$ 8 eGual %. 8 CE % evaluate to true i$ 8 i not eGual to %. 8 = % evaluate to true i$ 8 i greater t"an %. 8 =E % evaluate to true i$ 8 i greater t"an or eGual to %.

Le

t"an A;B

Le t"an or eGual A;EB

operand. Evaluate to true i$ le$t operand i le t"an rig"t operand. Evaluate to true i$ le$t operand i le t"an or eGual to rig"t operand.

8 ; % evaluate to true i$ 8 i le t"an %. 8 ;E % evaluate to true i$ 8 i le t"an or eGual to %.

E/,M0LES1 , EE , 7ould return T<1E. , CE , 7ould return (-LSE. AT"e tatement >(ive i not eGual to $ive.> i patentl% $al e.B , ;E , 7ould return T<1E. A(ive i le t"an or eGual to $ive. More preci el%9 it> e8actl% eGual to $ive9 but JavaScript could care le about boring detail li@e t"at.B

-.3. Selected ,rit"metic .perator


-rit"metic operator ta@e numerical value Aeit"er literal or variable B a t"eir operand and return a ingle numerical value. T"e tandard arit"metic operator are addition ALB9 ubtraction A)B9 multiplication AQB9 divi ion A5B and remainder ASB. T"e e operator 7or@ a t"e% do in ot"er programming language 9 a 7ell a in tandard algebra. Since programmer $reGuentl% need to add or ubtract 1 $rom a variable9 JavaScript "a "ortcut $or doing t"i . m%VarLL add one to t"e value o$ m%Var9 7"ile m%Var)) ubtract one $rom m%Var. E/,M0LES1 Let 8 E 3. =>> bump 8 up to '9 7"ile =22 ma@e 8 eGual to 2.

-.'. Logical .perator


Logical operator ta@e +oolean AlogicalB value a operand and return a +oolean value. T"at i 9 t"e% evaluate 7"et"er eac" ube8pre ion 7it"in a +oolean e8pre ion i true or $al e9 and t"en e8ecute t"e operation on t"e re pective trut" value . &on ider t"e $ollo7ing table? /perator 1 age e8pr1 TT and ATTB e8pr2 e8pr1 UU or AUUB e8pr2 not ACB Ce8pr De cription True i$ bot" logical e8pre ion e8pr1 and e8pr2 are true. (al e ot"er7i e. True i$ eit"er logical e8pre ion e8pr1 or e8pr2 i true. (al e i$ bot" e8pr1 and e8pr2 are $al e. (al e i$ e8pr i trueH true i$ e8pr i $al e.

E/,M0LES1 Since 7e "ave no7 learned to u e t"e e ential operator 9 7e can u e t"em in con2unction 7it" one anot"er. See i$ %ou can 7or@ out 7"% t"e $ollo7ing e8ample re olve t"e 7a% t"e% do? I$ 8 E ' and % E 09 AA8 L % L 2B EE 13B TT AAA8 L %B 5 2B EE 2B return (-LSE.

I$ 8 E ' and % E 09 AA% ) 8 L 4B EE 12B UU AA8 Q %B EE 2B return T<1E. I$ 8 E ' and % E 09 CAA852 L %B EE 4B UU AA8 Q A%52BB EE 2B return (-LSE.

2. 3 ing JavaScript .b4ect


!"en %ou load a document in %our 7eb bro7 er9 it create a number o$ JavaScript ob2ect 7it" propertie and capabilitie ba ed on t"e HTML in t"e document and ot"er pertinent in$ormation. T"e e ob2ect e8i t in a "ierarc"% t"at re$lect t"e tructure o$ t"e HTML page it el$. T"e pre)de$ined ob2ect t"at are mo t commonl% u ed are t"e *i do* and doc$%e t ob2ect . T"e *i do* "a met"od t"at allo7 %ou to create ne7 7indo7 7it" t"e ope (" and c-ose(" met"od . It al o allo7 %ou to create me age bo8e u ing a-ert("J co #ir%("J and pro%pt(". Eac" di pla% t"e te8t t"at %ou put bet7een t"e parent"e e . (or e8ample9 t"e $ollo7ing code?
a-ert((T!is is a a-ert ,o=("

...pop up an alert bo8 di pla%ing t"e given me age. Tr% it %our el$ b% clic@ing on t"i lin@. T"e doc$%e t ob2ect model t"e HTML page. T"e doc$%e t ob2ect contain arra% 7"ic" tore all t"e component con tituting t"e content o$ %our 7eb page9 uc" a image 9 lin@ 9 and $orm . Dou can acce and call met"od on t"e e element o$ %our 7eb page t"roug" t"e arra% . T"e ob2ect in t"i pre)de$ined "ierarc"% can be acce ed and modi$ied. To re$er to peci$ic propertie 9 %ou mu t peci$% t"e propert% name and all it ance tor 9 pelling out t"e complete "ierarc"% until t"e doc$%e t ob2ect. - period9 >.>9 i u ed in bet7een eac" ob2ect and t"e name o$ it propert%. Renerall%9 a propert% 5 ob2ect get it name $rom t"e K-ME attribute o$ t"e HTML tag. (or e8ample9 t"e $ollo7ing re$er to t"e value propert% o$ a te8t $ield named text1 in a $orm named myform in t"e current document.
doc$%e t+%y#or%+te=tB+va-$e

(orm element can al o be acce ed t"roug" t"e a$orementioned #or%s arra% o$ t"e doc$%e t ob2ect. In t"e above e8ample9 i$ t"e $orm named myform 7a t"e $ir t $orm on t"e page9 and text1 7a t"e t"ird $ield in t"e $orm9 t"e $ollo7ing al o re$er to t"at $ield> value propert%.
doc$%e t+#or%sECF+e-e%e tsE<F+va-$e

(unction Acapabiltiie B o$ an ob2ect can imilarl% be acce ed u ing t"e period notation. (or e8ample9 t"e $ollo7ing in truction re et t"e 2nd $orm in t"e document.
doc$%e t+#or%sE<F+reset("8

&lic@ on one o$ t"e ob2ect belo7 to vie7 t"e Ket cape documentation on t"e peci$ic propertie and met"od t"at t"at ob2ect "a ?

5. (unction
(unction are one o$ t"e $undamental building bloc@ in JavaScript. - $unction i a JavaScript procedure )) a et o$ tatement t"at per$orm a peci$ic ta @. $unction de$inition "a t"e e ba ic part ?

T"e $unction @e%7ord - $unction name - comma) eparated li t o$ argument to t"e $unction in parent"e e T"e tatement in t"e $unction in curl% brace ? V W

5.1. %e$ining a (unction


!"en de$ining a $unction9 it i very important t"at %ou pa% clo e attention to t"e %nta8. 1nli@e HTML9 JavaScript i ca e en itive9 and it i ver% important to remember to enclo e a $unction 7it"in curl% brace V W9 eparate parameter 7it" comma 9 and u e a emi)colon at t"e end o$ %our line o$ code.

It> important to under tand t"e di$$erence bet7een defining and calling a $unction. De$ining t"e $unction name t"e $unction and peci$ie 7"at to do 7"en t"e $unction i called. Dou de$ine a $unction 7it"in t"e ;S&<I*T=...;5S&<I*T= tag 7it"in t"e ;HE-D=...;5HE-D= tag . In de$ining a $unction9 %ou mu t al o declare t"e variable 7"ic" %ou 7ill be calling in t"at $unction. Here> an e8ample o$ defining a $unction?
#$ ctio pop$pa-ert(" K a-ert(/T!is is a L a-ert ,o=+/"8

Kotice t"e parent"e e a$ter t"e $unction name. It i imperative t"at %ou include t"e e parent"e e 9 even i$ t"e% are empt%. I$ %ou 7ant to pa a parameter into t"e $unction9 %ou 7ould include t"at parameter in ide o$ t"e parent"e e . - parameter i a bit o$ e8tra in$ormation t"at cn be di$$erent eac" time t"e $unction i run. It i tored in a variable and can be acce ed 2u t li@e an% ot"er variable. Here> an e8ample o$ a $unction t"at ta@e a parameter?
#$ ctio a ot!erA-ert(*ord" K a-ert(*ord > / is t!e *ord t!at yo$ c-ic.ed o /"8 L

!"en %ou call t"i $unction9 %ou need to pa a parameter A uc" a t"e 7ord t"at t"e u er clic@ed onB into t"e $unction. T"en t"e $unction can u e t"i in$ormation. Dou can pa in a di$$erent 7ord a a parameter eac" time %ou call t"e $unction9 and t"e alert bo8 7ill c"ange appropriatel%. Dou>ll ee "o7 to pa a parameter a little later on. Dou can pa in multiple parameter 9 b% eparating t"em 7it" a comma. Dou 7ould 7ant to pa in a $e7 parameter i$ %ou "ave more t"an one variable t"at %ou eit"er 7ant to c"ange or u e in %our $unction. Here are t7o e8ample o$ pa ing in multiple parameter 7"en %ou are de$ining t"e $unction?
#$ ctio seco dA-ert(*ordJpass*ord" K co #ir%(*ord > / is t!e *ord t!at yo$ c-ic.ed o + T!e secret pass*ord is / > pass*ord"8

#$ ctio

t!irdA-ert(*ordJpass*ord" K co #ir%(*ord > / is t!e *ord yo$ c-ic.ed o + P-ease ta.e ote o# t!e pass*ordJ / > pass*ord"8

Dou>ll notice t"at t"e ame parameter are pa ed into bot" o$ t"e e $unction . Ho7ever9 %ou can pa in 7"atever value %ou 7ant to u e A ee t"i ame e8ample belo7 in calling t"e $unctionB.

5.2. &alling a (unction


&alling t"e $unction actuall% per$orm t"e peci$ied action . !"en %ou call a $unction9 t"i i u uall% 7it"in t"e +/DD o$ t"e HTML page9 and %ou u uall% pa a parameter into t"e $unction. - parameter i a variable $rom out ide o$ t"e de$ined $unction on 7"ic" t"e $unction 7ill act. Here> an e8ample o$ calling t"e ame $unction?
pop$pa-ert("8

(or t"e ot"er e8ample9 t"i i "o7 %ou ma% call it?
<A HRE&'(Mtop( o C-ic.'(a ot!erA-ert(/top/"(>top</A>

T"i 7ould bring %ou to t"e top o$ t"e page9 and bring up an alert bo8 t"at aid? Ftop i t"e 7ord %ou clic@ed onF Tr% it $or %our el$? top Here i t"e ame e8ample 7it" multiple parameter t"at 7a "o7n above?

<A HRE&'(Mtop( o C-ic.'(seco dA-ert(/a*eso%e/J/pa das/"(>a*eso%e</A> <A HRE&'(Mtop( o C-ic.'(t!irdA-ert(/co%p$ters/J/i sert/"(>co%p$ters</A>

Dou>ll notice in t"e code t"at di$$erent value $or t"e variable *ord and pass*ord are pa ed in. T"e e value "ere are 7"at t"e $unction 7ill need to per$orm t"e

action in t"e $unction. Ma@e ure t"at t"e value %ou pa in are in t"e correct order becau e t"e $unction 7ill ta@e t"em in and a ign t"e e value to t"e parameter in t"e parent"e e o$ t"e $unction declaration. /nce %ou pa value into %our $unction9 %ou can u e t"em "o7ever %ou 7ant 7it"in %our $unction. Tr% it $or %our el$? !"en %ou clic@ on t"e 7ord belo79 a con$irmation bo8 7ill pop up and t"en t"e lin@ 7ill bring %ou to t"e top o$ t"e page. a7e ome computer

6. I$7El e Statement
tatement e8ecute a et o$ command i$ a peci$ied condition i true. I$ t"e condition i $al e9 anot"er et o$ tatement can be e8ecuted t"roug" t"e u e o$ t"e e-se @e%7ord.
i#

T"e main idea be"ind i# tatement i embodied b% t"e entence? FI$ t"e 7eat"er> good tomorro79 7e>ll go out and "ave a picnic and Li a 7ill do cart7"eel )) el e9 7e>ll ta% in and &at"erine 7ill 7atc" TV.F - %ou can ee9 t"e idea i Guite intuitive and9 urpri ingl% enoug"9 o i t"e %nta8?
if (condition" K statements1 L

)or)

if (condition" K statements1 L else K statements2 L

A-n i$ tatement doe not reGuire an el e tatement $ollo7ing it9 but an el e tatement mu t be preceded b% an i$ tatement.B condition can be an% JavaScript e8pre ion t"at evaluate to true or $al e. *arent"e e are reGuired around t"e condition. I$ condition evaluate to true9 t"e tatement in statements1 are e8ecuted. statements1 and statements2 can be an% JavaScript tatement 9 including $urt"er ne ted i$ tatement . Multiple tatement mu t be enclo ed in brace .

Here> an e8ample?
if (*eat!er '' /good/" K go5o$t(*e"8 !ave5a5pic ic(*e"8 do5cart*!ee-s(Lisa"8 L else K stay5i (*e"8 *atc!5TN(Cat!eri e"8 L

18. Loop
Loop are an incredibl% u e$ul programming tool. Loop "andle repetitive ta @ e8tremel% 7ell9 e peciall% in t"e conte8t o$ con ecutive element . -rra% immediatel% pring too mind "ere9 ince arra% element are numbered con ecutivel%. It 7ould be Guite intuitive Aand eGuall% practicalB9 $or in tance9 to 7rite a loop t"at added 1 to eac" element 7it"in an arra%. Don>t 7orr% i$ t"i doe n>t ma@e a lot o$ en e no79 it 7ill9 a$ter %ou $ini " reading t"e tutorial. T"e t7o mo t common t%pe o$ loop are #or and *!i-e loop ?

18.1. $or Loop


- #or loop con titute a tatement 7"ic" con i t o$ t"ree e8pre ion 9 enclo ed in parent"e e and eparated b% emicolon 9 $ollo7ed b% a bloc@ o$ tatement e8ecuted in t"e loop. T"i de$inition ma%9 at $ir t9 ound con$u ing. Indeed9 it i "ard to under tand #or loop 7it"out eeing t"em in action. - #or loop re emble t"e $ollo7ing?
#or (initial-expression8 condition8 increment-expression" K statements L

T"e initial-expression i a tatement or variable declaration. ASee t"e ection on variable $or more in$ormation.B It i t%picall% u ed to initiali:e a counter variable. T"i e8pre ion ma% optionall% declare ne7 variable 7it" t"e var @e%7ord. T"e condition i evaluated on eac" pa t"roug" t"e loop. I$ t"i condition evaluate to true9 t"e tatement in statements are per$ormed. !"en t"e condition evaluate to $al e9 t"e e8ecution o$ t"e #or loop top . T"i conditional te t i optional. I$ omitted9 t"e condition al7a% evaluate to true.

T"e increment-expression i generall% u ed to update or increment t"e counter variable. T"e statements con titute a bloc@ o$ tatement t"at are e8ecuted a long a condition evaluate to true. T"i can be a ingle tatement or multiple tatement . -lt"oug" not reGuired9 it i good practice to indent t"e e tatement $rom t"e beginning o$ t"e #or tatement to ma@e %our code more readable. &"ec@ out t"e $ollo7ing #or tatement. It tart b% declaring t"e variable i and initiali:ing it to :ero. It c"ec@ 7"et"er i i le t"an nine9 per$orm t"e t7o ucce ive tatement 9 and increment i b% one a$ter eac" pa t"roug" t"e loop?
var ' C8 #or (var i ' C8 i < H8 i>>" K >' i8 a-ert((T!e va-$e o# is o* ( > L

"8

Tr% it %our el$? &lic@ t"i lin@

18.2. 9"ile Loop


T"e *!i-e loop9 alt"oug" mo t people 7ould not recogni:e it a uc"9 i #or> t7in. T"e t7o can $ill in $or one anot"er ) u ing eit"er one i onl% a matter o$ convenience or pre$erence according to conte8t. *!i-e create a loop t"at evaluate an e8pre ion9 and i$ it i true9 e8ecute a bloc@ o$ tatement . T"e loop t"en repeat 9 a long a t"e peci$ied condition i true. T"e %nta8 o$ *!i-e di$$er
while (condition" K statements L

lig"tl% $rom t"at o$ #or?

condition i evaluated be$ore eac" pa t"roug" t"e loop. I$ t"i condition evaluate to true9 t"e tatement in t"e ucceeding bloc@ are per$ormed. !"en condition evaluate to $al e9 e8ecution continue 7it" t"e tatement $ollo7ing statements. statements i a bloc@ o$ tatement t"at are e8ecuted a long a t"e condition evaluate to true. -lt"oug" not reGuired9 it i good practice to indent t"e e tatement $rom t"e beginning o$ t"e tatement. T"e $ollo7ing *!i-e loop iterate a long a n i le
var ' var = ' *!i-e( >>8 = >' C8 C8 < H" K 8

t"an t"ree.

a-ert((T!e va-$e o#

is ( >

> (+ T!e va-$e o# = is ( > ="8

Tr% it $or %our el$? &lic@ t"i lin@

11. &ommenting
&omment allo7 %ou to 7rite note to %our el$ 7it"in %our program. T"e e are important becau e t"e% allo7 omeone to bro7 e %our code and under tand 7"at t"e variou $unction do or 7"at %our variable repre ent. &omment al o allo7 %ou to under tand %our code i$ it> been a 7"ile ince %ou la t loo@ed at it. In JavaScript9 %ou can 7rite bot" one)line comment and multiple line comment . T"e notation $or eac" i di$$erent t"oug". (or a one line comment9 %ou precede %our comment 7it" 55. T"i indicate t"at ever%t"ing 7ritten on t"at line9 a$ter t"e 559 i a comment and t"e program "ould di regard it. (or a multiple)line comment9 %ou tart 7it" 5Q and end 7it" Q5 . It i nice to put an Q at t"e beginning o$ eac" line 2u t o omeone peru ing %our code reali:e t"at "e5 "e i loo@ing at a comment Ai$ it i reall% long t"i "elp B. T"i i not nece ar% t"oug". T"e $ollo7ing are e8ample o$ comment in JavaScript.
// T!is is a si g-e -i e co%%e t+ /; T!is is a %$-tip-e -i e co%%e t *it! o -y o e -i e+ ;/ /; T!is is a %$-tip-e -i e co%%e t+ ; T!e star (;" at t!e ,egi i g o# t!is -i e is optio a-+ ; So is t!e star at t!e ,egi i g o# t!is -i e+ ;/

12. .n)Line Help


(or more detailed e8planation or $urt"er "elp9 ee Ket cape> JavaScript <e$erence Ruide $or JavaScript 1.1. Ma@e ure t"at i$ %ou con ult ot"er ource t"at t"e% are re$ering to JavaScript 1.1. T"i i t"e ver ion t"at i compatible 7it" Ket cape 3.69 o i$ %ou u e code t"at i not recogni:ed b% JavaScript 1.19 it 7ill not 7or@ 7"en %our paged i bro7 ed in Ket cape 3.6.

H/ME This tutorial was adapted from the Netscape Reference Source for CS2 at Brown niversity! Spring 1""#! $y %isa Co&&ens! 'manda (udler! and )&el Sulam

)t was slightly modified for use in ' Bridge to Computer Science! Summer 1""#! $y %isa Co&&ens*

Vous aimerez peut-être aussi