Quick In Just 3 Daysindex-of.co.uk/Programming/Quick JavaScript Learning.pdfChapter 1 JavaScript...
Transcript of Quick In Just 3 Daysindex-of.co.uk/Programming/Quick JavaScript Learning.pdfChapter 1 JavaScript...
QuickJavaScriptLearning
InJust3Days
(Fast-TrackLearningCourse)
By
VijayK.R.
DisclaimerCopyright©ByVijayK.R.
Thepublisherandtheauthorofthispublicationhaveutilizedtheirbesteffortstomaintaintheaccuracyofallthecontents.ThecontentinthiseBookisintendedtobeusedonly for educational purposes. No part of this eBook can be copied, reconstructed orrewrittenbyanymeans,electronic,Photostatorbyanymode,withoutthewrittenconsentoftheauthorandthepublisher.
The readers are completely responsible for all the actions taken by reading thecontentofthisbook.Theauthorandthepublisherholdnoresponsibilityforanydamage,lossordisruptionbecauseofomissionsorerrors,toanyparty.
The author and the publisher disclaim any liability regarding the effectiveness,performanceorapplicabilityofanythinginthiseBook.
TableofContentIntroduction……………………………………………4
Chapter1:JavaScriptStarts……………..…….5
Chapter2:JavaScriptOutput/DisplayCodes……………………………………………………..9
Chapter3:JavaScriptVariables,Statements,Comments&Keywords………………….…….14
Chapter4:JavaScriptDataTypes&Operators……………………………………………….25
Chapter5:JavaScriptFunctions………………32
Chapter6:JavaScriptObjects…………..….…36
Chapter7:JavaScriptArrays……………………43
Chapter8:JavaScriptConditions(if,else&switch)andLoops(for,while&dowhile).46
Summary…………………………………………………61
Introduction
JavaScriptisonethelanguagewhichhelpsyoumakebrowsertodowhatyouwanttodo.ThisiseasylanguagetolearnandIamgoingtoteachyounow.MylanguagewillbeuserfriendlyandIwilltrytotelldifficultstuffsineasylanguagewithexamples.Let’smove on one by onewith JavaScript lessons. This is 3 days basic JavaScript LearningCourse.
BeforestartingJavaScript,IamassumingthatyouhaveatleastbasicknowledgeofHTML&CSS.Ifyoudon’thaveknowledgeofHTML&CSS,thenyoushouldgoandstudythatfirstviaonlinetutorials.YoumaybeabletolearnbasicHTML&CSSin2-3days.
Day1=LearnChapter1&2
Day2=LearnChapter3,4&5
Day3=LearnChapter6,7&8
Chapter1JavaScriptBasics
JavaScriptcanchangeHTMLContents. IfyouarePHPdeveloperand ifyouwant togetdonesomeworkwithoutpageloadsoryouwantHTML&CSStoperformworkthenyouwillneedJavaScript.
<script>Tag
JavaScriptcanbeplacedinsidebodyandheadtag.TheJavaScriptcodesshouldbeinside<script>and</script>tags.
<script>
document.getElementById(“demo”).innerHTML=“MyFirstJavaScriptCode”;
</script>
JavaScriptEventsJavaScriptcodesaretriggeredonevents.Eventsareperformedwhenapersonperform
an event. There are many events provided by browser like onclick, onmouseover,onkeyup,onkeydown,ondoubleclickandmanymore.WhenanyofeventsperformsthenJSCodestriggeredanddosomethingaccordingtocodes.
<buttononclick=“myFunction()”>PressMe!</button>
Explanation–here,onclickiseventandmyFunction()isJSfunction.
JavaScriptFunctionJavaScriptblockofcodeswhichisinside<script>and</script>tagswhichareusedto
performsomeworkiscalledfunction.
<script>
functionmyFunction(){
document.getElementById(“demo”).innerHTML=“MyFirstJavaScriptCode”;
}
</script>
Explanation–HeremyFunction()istheJSfunctioninside<script>tags.
BestPlaceforJSCodesItisbestpracticetouseallJScodesinside<head>tags.
<html>
<head>
<script>
functionmyFunction(){
document.getElementById(“demo”).innerHTML=“Paragraphhaschanged.”;
}
</script>
</head>
<body>
<h1>NewPage</h1>
<pid=“demo”>ThisisaParagraph</p>
<buttontype=“button”onclick=“myFunction()”>PressMe!</button>
</body>
</html>
Explanation–Weusedallscriptinsideheadtags.
ExternalJSFiles
Youcanshoreallcodesinoneanotherfileandsavefilewith.jsextension.Youmustincludethefileinside<head>tagsbythissyntax.
<head>
<scriptsrc=“newScript.js”></script>
</head>
Explanation–Here,weusednewScript.jsfile,wherewestoredallJScodes,whenanyfunctionisinvokedthecodeswillbetriggereddirectlyfromthenewScript.jsfile.
Chapter2JavaScriptDisplay&OutputCodes
JavaScriptusesfourwaystodisplayoutput.
1stWay:document.write()Itisusedtowriteoroutputanythinginthewebpage.
<html>
<head>
<script>
functionadd(){
document.write(6+6);
}
</script>
</head>
<body>
<h1>MyFirstCode</h1>
<buttononclick=“add()”>PressMe!</button>
</body>
</html>
Explanation–WhenyouclickonPressmebutton,document.writeshowsoutputinthewebpage.
2ndWay:Window.alert()
Itisusedtodisplaymessageinalertbox.
<html>
<body>
<h1>MyAlertWebPage</h1>
<script>
window.alert(“Warning”);
</script>
</body>
</html>
Explanation – When you open the webpage, you will see an alert box containingWarning.
3rdWay:innerHTMLThismethodisusedforwritingsomethinginsideHTMLelementlikeinsideparagraph,
textbox,textareaandetc.
<html>
<head>
<script>
functionsomething(){
document.getElementById(“demo”).innerHTML=“ThisparagraphisfilledwithtextNow”;
}
</script>
</head>
<body>
<h1>WriteInsideHTMLElementParagraph</h1>
<pid=“demo”>Pisblanknow</p>
<buttononclick=“something()”>PressMe!</button>
</body>
</html>
Explanation–whenyouclickPressMe,document.getElementByIdtakesiddemoandwritesinsidedemoidthroughinnerHTMLkeyword.
4thWay:console.log()Itisusedtowriteinsideconsole,clickonF12functionkeyinyourfirefox,chrome,IE
browser.Youwillseeoneconsoletag.Clickontab,youwillgetthemessagewhichyouwriteinconsole.log().Seeexample.
<html>
<head>
<script>
console.log(2+2);
</script>
</head>
<body>
<h1>ClickF12functionkeyandgotoconsoletagtoseeresults</h1>
</body>
</html>
Chapter3JavaScriptVariables,Statements,Comments,Keywords
JavaScriptVariablesVariablesareusedtostoreddatainanylanguage.InJavaScript,variablesdothesame
likeCandotherhighlanguages.Variablesarestoredintheformofdatatypeslikeint,strandetc.howeveratJS,youcanusevarkeywordforalltypesofdatatypes.
WritingString:Forwritingstring,youneedtousesingleordoublequote.
Example:
varx=“ThisisaBoy.”;
vary=‘ThisisaGirl.’;
Note:semicolon“;”isusedtoendtheline.
WritingNumeric:Forwritingnumeric,youneednot tousedoubleorsinglequotes. IfyouuseitthenJSwilltakeitasstring.
Example:
varx=8;
vary=6;
varz=x+y;
JavaScriptStatements
JavaScriptstatementsaresetofinstructionswhichareexecutedbybrowser.
Example1:ChangeHTMLContent
Thinkofthescenario;ifyouwanttoaddsomecontentonanywhereinHTMLbyclickingonebutton.
YoucandothisworkeasilythroughPHPbutthepagewillbereloaded.WiththehelpofJavaScriptyoucando thisworkwithoutpagereloads.Here,JavaScriptcomeatexistencewhenweneedtoperformanyworkbybrowser.
<html>
<body>
<h1>ChangeContentofBox<h1>
<pid=“demo”>JavaScriptwillchangeHTMLcontent.</p>
<buttontype=“button”
onclick=“document.getElementById(‘demo’).innerHTML=‘Ilearntfirstexample!’”>
PressMe!</button>
</body>
</html>
Explanation–Here, Imadeonparagraphwithhtmlptagandgave idname“demo”.Secondly I made one button with onclick event. I wrote one JavaScript code“document.getElementById(‘demo’).innerHTML = ‘I learnt first example!’. You willlearnalltheseincomingchaptersbutlet’sstartnow.documentisJavaScriptobjectandgetElementById is documentmethod. It clearly shows that get element by id (demo).Here,itwillgetelementbyiddemowhichistheidofptagandtheninnerHTMLtellsthatinsidethepHTMLtagmakechanges.Andyouhavetoperformthechangewhichiswrittenafterequaltosign.Nowwhenyoupressthebutton<pid=“demo”>innerhtmltagischanged to“I learnt firstexample!”. Ihopeyouwillget this, ifnot read it againand
evennot.Notaproblem,wewillseemanyexamplesaheadtoknowallthese.
Example2:ChangeCSSStyle
IfyouwanttochangethecolorofsometextinHTMLpagebyclickingonebuttonthen you can do this work easily through JavaScript. I am going to show you colorchanginginexample.
<html>
<body>
<h1>ChangeColorofparagraph<h1>
<pid=“demo”>JavaScriptwillchangethecolor.</p>
<script>
functioncolorChange(){
varx=document.getElementById(“demo”);
x.style.color=“red”;
}
</script>
<buttontype=“button”onclick=“colorChange()”>PressMe!</button>
</body>
</html>
Explanation–Ifyoureadthefirstexample,youcanunderstandtheparagraphptagidisdemoandbuttononclickevent.Inpreviousexample,wehavewrittenthecodedirectlyoneventnameonclick.Asthecodewassmallsowewroteinline,butnowcodeisbigsoweused <script> </script> tag to write JavaScript code. Inside the code, we made onefunctionnamedcolorChange()andopenthefunctionwithcurlybracket‘{‘andclosethefunction with ‘}’ bracket. I will teach you regarding function in later chapters. For
understandingit,justassumethatfunctionistheplacewherewewritecodewhichwecanuse atmanyplaces.Function alwayshasonename, and function is calledby its name.Now come to example, here at onclick event we called the function by its namecolorChange().Andwhenthiseventtriggeredthanitwillworkaccordingthecodewhichiswritteninsidethefunctionopencurlybracket{andclosecurlybracket}.
Here,wehavetakenonevariablex.VariableisdefinedbykeywordvarinJavaScript.Weassigneddemotagtovariablexandinnextlinex.style.color says thatxstylecolorwillbechangedtoredwhenitiscalled.Andwhenyoupress“PressMe!”buttonthecoloroftextwillbechanged.Justuseitandyouwillstartlearningitautomatically.Ifnotthenclose your eyes for a couple ofminutes and think of this code. Youwill start gainingknowledge.
Example3:ChangeHTMLAttributes
Think,ifyouwanttochangeimagetodifferentimagewithoneclick.Let’slookonthisexamplefornow.Ifyoujustkeeplittleattentiononprevioustwoexamples,youwillgainmanythingswhichwillhelpyougoahead.Ifyouarestudyinginhurry,waitandwatchtheprevioustwoexamples.Ifyouunderstandthebasics,youwon’tfeelanydifficultyincomingcodes.Nowcomeontheexample.
<html>
<body>
<h1>JavaScriptwillChangeImages</h1>
<imgid=“myImage”src=“https://upload.wikimedia.org/wikipedia/en/c/c2/Single_red_rose.jpg”width=“100”height=“180”>
<script>
functionchangeImage(){
varimage=document.getElementById(‘myImage’);
if(image.src.match(“red_rose”)){
image.src=“https://upload.wikimedia.org/wikipedia/commons/c/c3/Extracted_pink_rose.png”;
}else{
image.src=“https://upload.wikimedia.org/wikipedia/en/c/c2/Single_red_rose.jpg”;
}
}
</script>
<buttononclick=“changeImage()”>PressMe!</button>
</body>
</html>
Explanation–Here,ItooktwoimagesfromWikimediafirstimageisredroseandsecondispinkrose.Youcanuseyourimages.
Myredroseimage–
https://upload.wikimedia.org/wikipedia/en/c/c2/Single_red_rose.jpg
Mypinkroseimage-https://upload.wikimedia.org/wikipedia/en/c/c2/Single_red_rose.jpg
Whenweclickonbutton,theimagegetschangedtodifferentimage.NowmovetocodeinsidefunctionchangeImage().Herewehaveusedifandelseconditions,Iwillteachitinlater chapters.Forhere, think that if image.src.matchmeans (image sourcematches tored_rosewordwhich iswritten in the url) then itwill show red rose, and if itwill notmatchthenitwillshowelsepartwhichisimage.src(meansimagesourceofpinkrose).
JavaScriptComments
JavaScriptcommentsareusedtocommentoncodesectionsforfuturereferences.Afterwritingmanycodes,weforgettheideaofwritingcodesandwithcomments,wecaneasilyrememberwhatthecodeisandwhywewroteanyspecificcode.
TherearetwotypesofcommentinginJS.
1. SingleLineComments://isusedforsinglelinecomments.
Example:
varx=5;//thisisthevalueofx
vary=6;//thisisthevalueofy
2. MultiLineComments:Multilinecommentsareusedtocommentmorethanoneline.Itstartswith/*andendswith*/.
Example:
varx=5;
vary=6;
/*
Here,valueofxis5and
Valueofyis6
*/
JavaScriptKeywords
KeywordsarewordswhicharereservedbyJStoperformcertaintasks.Youcannotusekeywordasvariable.Keywordlist
Keywords Description
Var Fordeclaringavariable
Break Terminatesaswitchlooporanotherloop
continue Jumpsoutofaloopandstartsatthetop
debugger StopstheexecutionofJavaScript
do…while Executetheblockofstatements
for Blockofstatementstobeexecuteduntilconditionistrue
function Declaresafunction
if…else Blockofstatementstobeexecuted,dependingonacondition
return Exitsafunction
switch Blockofstatementstobeexecutedwhichdependsondifferentcases
try…catch Implementserrorhandlingforstatementblocks
Chapter4JavaScriptDataTypes&Operators
JavaScriptDataTypes
JavaScript Data Types can be string, number, Boolean, object, array and manymore.Itisveryimportanttohavedatatypes,withoutdatatypescomputersinvolveinrisk.
1. JSStringDataTypes -Stringdata types always inside single or doublequotes.
Example:
varname=“John”;
varname=‘John’;
2. JSNumberDataTypes-Itisnumericdatatypes.
Example:
varx=5;
vary=6;
3. JSBooleanDataTypes – It is conditional data type, it is either true orfalse.
Example:
varx=true;
vary=false;
4. JSArraysDataTypes–Itiswritteninbracketandseparatedbycomma.
Example:
varlanguage=[“php”,“javascript”,“java”];
5. JS Object Data Types – It is written in curly braces & separated bycomma,anditssyntaxis-(Propertyname:value)
Example:
varman={name:”Bonnie”,age:50,surname:”smith”};
TypeofOperator
Wecanknowdatatypeofanyoperatorwithtypeofkeyword.
Example:
typeof“bonnie”//itwillreturnstring
typeof50//itwillreturnnumber
typeoftrue//itwillreturnBoolean
typeof[“man”,“women”]//itwillreturnarray
typeof{name:”Jonnie”,age:50}//itwillreturnobject
Undefined,EmptyandNull
1. UndefinedDataTypes–Datatypeswhicharenotdefinedwithanyvaluecalledundefineddatatypes.
Example:
varx;//xisundefined
varBonnie;//Bonnieisundefined
2. Empty
Example:
varx=““;//xisemptyvalue
3. Null–Nullisnothingbuttypeisanobject.
Example:
varx=null;//xisnull
JavaScriptOperators
JavaScript hasmany operators like arithmetic operators, assignment operators, stringoperators,logicaloperatorsandcomparisonoperators.
1. Arithmetic Operators – Operators which are used to perform certainmathematicoperationsonnumberscalledarithmeticoperators.
Example:
ArithmeticOperator Descriptions
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
— Decrement
2. AssignmentOperators – For assigning value, assignment operators areused.
Example:
Operator
=
+=
-=
*=
/=
%=
3. StringOperators–Youcanaddstringswith+operator.
Example:
varname=“Jonnie”;
varsurname=“Smith”;
varfullname=“Jonnie”+“Smith”;
4. Comparison&LogicalOperators
Example:
Operators Description
== equalto
=== equalvalueandequaltype
!= notequal
!== notequalvalueornotequaltype
> greaterthan
< lessthan
Chapter5JavaScriptFunctions
Functionisablockofcodewhichisusedtoperformanytaskandcanbereusedinmanyplaces.Functionisinvokedwhenitiscalled.Syntaxissimple,hereitis:
Syntax:
functionmyFun(parameter1,parameter2,parameter3,…)
{
//blockofcode
}
Here,myFun is function name and parameter1, parameter2 and parameter 3 areparameters, which are optional, then a curly bracket starts and ends. In between curlybracket,therewillbecodewhichwillbeexecutedwhenthefunctionwillbecalled.
Example:
<html>
<head>
<script>
functionmyFun(x,y){
varx;
vary;
varz=x+y;
document.getElementById(“demo”).innerHTML=z;
}
</script>
</head>
<body>
<pid=“demo”></p>
<buttononclick=“myFun(5,10)”>PressIT!</button>
</body>
</html>
Here,whenweclickthebutton“PressIT”,anonclickeventisgeneratedandmyFun(5,10)functionhasexecuted.When the functionexecuted,wepass twoparameters to functionwithvaluesandthosevaluesbecomesxandyvalueoffunction,andfinallyresultsstoredinvariableandzvariabledatagoesinsidetheptag.
FunctionreturnFunctionisstopexecutingwhenitreachestoreturnstatement.ReturnisJavaScript
inbuiltstatementtostoppingtheexecutionandsendingthereturnvaluetofunction.Youcanthinkasthe“overallvalueoffunction”canbedenotedbyreturnstatement.
Example
<html>
<head>
</head>
<body>
<pid=“demo”></p>
<script>
functionmyFun(x,y){
varx;
vary;
varz=x+y;
returnz;
}
document.getElementById(“demo”).innerHTML=myFun(150,10);
</script>
</body>
</html>
Here,myFun(150,10)valuewillbeassignedtodemoid.Here,youhaveseenthatIhavewritten script inside the body tag, because head tags are executedwhen it is called butbody tagsareautomaticallyexecutedwhenbody is loadedonbrowser.Here, Ihavenotgivenanyeventlikeonclick,thereforeIhavewrittenentirescriptinsidethebodytag.
Chapter6JavaScriptObjects
Thinkobjectsastherealobject,forexamplecarisanobject.Whichcanperformanytask;ithasitspropertiesandmethods.Propertieslikeitscolor,model,weightandmethodlikesstart,stopandetc.
ObjectPropertiesExample
varcar={color:”red”,model=“5520”,weight=“900kgs”};
Propertiesareinvokedbytwotypesofsyntaxes.
1stsyntax=Object.property;
2ndSyntax=Object[“property”];
Example:
<html>
<head>
</head>
<body>
<pid=“demo”></p>
<script>
varcar={color:“red”,model:552,weight:“900kgs”};
document.getElementById(“demo”).innerHTML=car.color;
</script>
</body>
</html>
ObjectMethodObjectmethodisafunctioninsidetheobjectwhichhastoperformcertaintask.Its
syntaxtoinvokedis=object.method();
Example:
<html>
<head>
</head>
<body>
<pid=“demo”></p>
<script>
varcar={
color:“red”,
model:552,
weight:“900kgs”,
fullDetails:function(){
return“Carcoloris“+this.color+“.Carmodelis“+this.model+”andCarweightis“+this.weight;}
};
document.getElementById(“demo”).innerHTML=car.fullDetails();
</script>
</body>
</html>
Here,amethodfullDetailsismadeasafunctionanditisinvokedbycar.fullDetails().Here, you have seen new keyword “this”. “this” is used to use own properties of anyobject. You cannot directly write color, model and weight. You need to use this.color,this.modelandthis.weighttouseinsidethefunction.
ObjectConstructorItisbestwaytouseconstructorforusingobjectswithparameters.
functionperson(name,age,weight,height){
this.name=name;
this.age=age;
this.weight=weight;
this.height=height;
}
Herepersonistheconstructorobject
CreateanobjectForcreatinganobject,newkeywordisusedinJavaScriptasitisusedinPHP,C
andinmanylanguages.
varmyFriend=newperson(Jonnie,Smith,50kg,6ft);
Here,myFriendisnewobjectofpersonObject.Now,myFriendcanaccesswholepropertiesandmethodsofobjectperson.
myFriend.name//accessingproperty
myFriend.age//accessingproperty
JavaScriptPrototypes
AllJavaScriptobjectsareinheritedwiththeirobjectprototypeswhicharedenotedlikeobject.prototype.Example:newDate()isusedtocreatenewDateobjectandinheritDate.prototype.
CreatingaPrototype
functionperson(firstname,surname,age){
this.firstname=firstname;
this.surname=surname;
this.age=age;
}
Creatingnewobjectswithnew keywordvarstudent=newperson(“John”,“Smith”,12,“blue”);
AddingProperties,Methodsto ObjectsSometimeyouwanttoaddsomeproperties,methodstoobjects,allexistingobjects
ortoaprototypeobject.
Addingpropertytoanobject
student.haircolor=“Gray”;
Addingpropertytoaprototype
Youcannotdirectlyaddpropertytoaprototypeassimilartoobject.Youneedtodobythisway.
person.haircolor=“Gray”;
Addingmethodtoanobject
student.fullname=function(){
returnthis.firstname+““+this.surname;
};
Addingmethodtoaprototype
functionperson(firstname,surname,age){
this.firstname=firstname;
this.surname=surname;
this.age=age;
this.fullname=function(){
returnthis.firstname+““+this.surname;};
}
Chapter7JavaScriptArrays
JavaScriptArraysareusedtostoremultiplevaluesinonevariable.
Example:
varcars=Array(“BMW”,“Volvo”,“Jeep”);
varcars=newArray(“BMW”,“Volvo”,“Jeep”);
Arrayaremadewithorwithoutnewkeyword,herethreevaluesarestoredincarsvariable.
cars[0]=“BMW”
cars[1]=“Volvo”
cars[2]=“Jeep”
Itmeansallvaluesareactuallyindexofonevariable“cars”.Itmeansarraystoresmultiplevaluesintheformofindexes.
Ifyouwouldliketoaccessanyarraythenyoucansimplyaccessbywritingitsindex.
Example:
<html>
<head>
</head>
<body>
<pid=“demo”></p>
<script>
varcars=Array(“BMW”,“Volvo”,“Jeep”);
document.getElementById(“demo”).innerHTML=cars[1];
</script>
</body>
</html>
AccessinganarrayYoucanaccessanyarraywiththeirindexvaluesdirectlyandindirectly.
varcarname=cars[0];
or
cars[0];
ArraysasObjectsObjects uses name indexeswhereas array uses numbered indexes.Means, array uses
numberstoaccesselementswhereasobjectusesnamestoaccesselements.
Example
varperson=[“John”,“Smith”,12];//array
varperson={firstname:“John”,lastname:“Smith”,age:12};//object
Chapter8JavaScriptConditions(if,else,elseif&Switch)andLoops
(for&while)
JavaScriptConditions(if,else,elseif &switch)InJavaScript,many timesyouhave tochooseoneconditionormanyconditions
forperforminganytask.
Syntax
If(condition){
Blockofcodewillexecute,whenifconditionbecomestrue.
}else{
Blockofcodewillexecute,whenifconditionbecomesfalse.
}
Usingifstatement
Whenyouhavetoperformonetaskonanycondition,and“if”conditionbecomestruethen“ifstatementblock”willexecute.
UsingelsestatementWhen“if”conditionbecomesfalse,then“else”blockwillbeexecuted.
Example:ifageisabove18thenthepersoncanvoteandifthepersonbelow18agethencannotvote.
<html>
<head>
<title>VoteEligibility</title>
</head>
<body>
<div>VoteEligibility</div>
<script>
functionmyfunction(){
varage=document.getElementById(“age”).value;
if(age>=18){
vareligibility=“thispersoncanvote”;
document.getElementById(“demo”).innerHTML=eligibility;
}else{
vareligibility=“thispersoncannotvote”;
document.getElementById(“demo”).innerHTML=eligibility;
}
}
</script>
EnterYourAge:<inputtype=“text”id=“age”name=“age”/><br>
<pid=“demo”></p>
<inputtype=“button”onclick=“myfunction()”value=“CheckEligibility”>
</body>
</html>
UsingelseifstatementWhenwehavemorethanoneconditionthenweuse“elseif”statement.
Syntax:
If(condition1){
Blockofcodewillexecute,whenifcondition1becomestrue.
}elseif(condition2){
Blockofcodewillexecute,whenifcondition2becomestrue.
}else{
Blockofcodewillexecutewhenbothconditionsbecomesfalse.
}
Example:ifapersonmeetsbefore12hours,wewishhimgoodmorning,ifhemeetsafter16hours,wewishhimgoodafternoonandifboththeconditionsbecomefalsethenwewishgoodevening.
<html>
<head>
<title>Example</title>
</head>
<body>
<div>GreetMessage(EnterTimein24hoursformat)</div>
<script>
functionmyfunction(){
vartime=document.getElementById(“time”).value;
if(time<12){
vargreet=“GoodMorning”;
document.getElementById(“demo”).innerHTML=greet;
}elseif(time<16){
vargreet=“GoodAfternoon”;
document.getElementById(“demo”).innerHTML=greet;
}else{
vargreet=“GoodEvening”;
document.getElementById(“demo”).innerHTML=greet;
}
}
</script>
EnterTime:<inputtype=“text”id=“time”name=“time”/><br>
<pid=“demo”>GreetMessageHere:</p>
<inputtype=“button”onclick=“myfunction()”value=“CheckGreetMessage”>
</body>
</html>
Bythiswecanincreaseasmanyaselseifconditionsinthecode.Formanyconditionswecanalsouseswitchstatement.
SwitchStatementSwitchstatementisusedwhenyouhavemanyconditionstocheck.Youcandothe
sameworkwithelseifbutswitchisbetterthanelseifstatement.Youneedtoput“break”command after each condition and one conditionwill “default” if no conditionwill beexecuted.
Syntax:
switch(expression){
casex:
thiscodeblockwillexecute.
break;
casey:
thiscodeblockwillexecute.
break;
default:
thiscodeblockwillexecute.
}
Example:
<html>
<head>
<title>Example</title>
</head>
<body>
<script>
functionmyfunction(){
vartoday=newDate().getDay();
switch(today){
case0:
day=“TodayisSunday”;
break;
case1:
day=“TodayisMonday”;
break;
case2:
day=“TodayisTuesday”;
break;
case3:
day=“TodayisWednesday”;
break;
case4:
day=“TodayisThursday”;
break;
case5:
day=“TodayisFriday”;
break;
case6:
day=“TodayisSaturday”;
break;
}
document.getElementById(“demo”).innerHTML=day;
}
</script>
WhatDayisToday:
<pid=“demo”></p>
<inputtype=“button”onclick=“myfunction()”value=“CheckToSeeToday’sDay”>
</body>
</html>
JavaScriptLoopsJavaScriptLoops are used to execute one codemany times by changing values.
Forexample,youwanttowrite1to1000inonepageineachline.Bydoingmanually,itwilltakehugetimebutwithloops,itwillbedoneinfewseconds.
Example:
<html>
<head>
<title>Example</title>
</head>
<body>
<script>
functionmyfunction(){
varstar=””;
for(vari=1;i<1000;i++){
star+=i+“<Br>”;
}
document.getElementById(“demo”).innerHTML=star;
}
</script>
<pid=“demo”></p>
<inputtype=“button”onclick=“myfunction()”value=“CheckLoop”>
</body>
</html>
ForLoopInthepreviousexample,yousawthatloopneedsthreestatements.
Firststatement–toinitializethevalue
Secondstatement–tocheckthecondition
Thirdstatement–toincreaseordecreasethecounter
Syntax:
for(statement1;statement2;statement3){
Thiscodeblocktobeexecuted
}
In the previous example, loop begins with statement 1 which is var i=1, here we areinitializing the value of “i” and then statement 2 checks the condition, if condition isfulfilled then block of code executes. Here statement 3 works after block of codeexecution,thenstatement3workstoincreaseordecreasethevalueof“i”.
WhileLoopWhenweneedtoexecutetheblockofcodewhenanyconditionfulfillsthenwe
usewhileloop.
Syntax:
while(condition){
Thiscodeblocktobeexecuted
}
Example:
<html>
<head>
<title>Example</title>
</head>
<body>
<script>
functionmyfunction(){
varnum=””;
vari=1;
while(i<20){
num+=“Numberis”+i+”<Br>”;
i++;
}
document.getElementById(“demo”).innerHTML=num;
}
</script>
<pid=“demo”></p>
<inputtype=“button”onclick=“myfunction()”value=“CheckLoop”>
</body>
</html>
Here,whilechecksthestatement,andexecutethecodeandthenincreasethevalueof“i”andagainchecksthestatementandexecutethecodeandsoon…
DowhileLoopdowhileloopisusedwhenyouneedtoexecutetheblockofcodeatleastonetime,
firstdostatementworksandthenwhilestatementchecksthecondition.
Syntax:
do{
Thisblockofcodewillexecute.
}while(condition)
Example:
<html>
<head>
<title>Example</title>
</head>
<body>
<script>
functionmyfunction(){
varnum=””;
vari=1;
do{
num+=“Numberis”+i+”<Br>”;
i++;
}
while(i<10);
document.getElementById(“demo”).innerHTML=num;
}
</script>
<pid=“demo”></p>
<inputtype=“button”onclick=“myfunction()”value=“CheckLoop”>
</body>
</html>
Here,firstlydostatementsworksandthenchecksthecondition,ifconditionbecomestruethenagaindostatementcodeexecutes.
Summary
Youhavesuccessfully learntJavaScript,nowmakeyourownJScodesandworkinrealworkingscenario.Ihopeyouenjoyedthisthreedayscourse.