Java Script Notes1
Java Script Notes1
SCRIPT
A script is a small piece of program that can add interactivity to the website. For example, a
scriptcouldgenerateapop-upalertboxmessage,[Link] be
JavaScript or VBScript.
Ascriptlanguageisasimpleprogramminglanguagewithwhichyoucanwritescripts.
A scripting language is a form of programming language that is usually interpreted rather
thancompiled.
Conventionalprogramsareconvertedpermanentlyintoexecutablefilesbeforetheyarerun. In
contrast, programs in scripting language are interpreted one command at a time. Scripting
languages are often written to facilitate enhanced features of Web sites.
JavaScript,Perl,PHP,Python,VBScriptarethemostpopularexamplesofscriptingLanguages.
WhatisClientsideScript?
Aclient-sidescriptisasmallprogram(orsetofinstructions)thatisembedded(orinserted) into a
web page. It is processed within the client browser instead of the web server.
Theclientsidescriptdownloadsattheclientendfromtheserveralong withtheHTMLweb
[Link] the
results on the monitor.
The script that executes on the user’s computer system is calledclient. It is embedded (or
inserted)withintheHTMLdocumentorcanbestoredinanexternalseparatefile(knownas external
script).
The script files are sent to the client machine from the web server (or severs) when they are
[Link]’swebbrowserexecutesthescript,thendisplaysthewebpage,including any
visible output from the script.
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
Clientsidescriptsmayalsohavesomeinstructionsforthewebbrowsertofollowinresponseto certain
user actions, such as pressing a page button. They can often be looked if client want to view the
source code of web page.
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
WhatisJavaScript?
JavaScript isadynamiccomputerprogramminglanguage.
It is lightweight and most commonly used as a part of web pages, whose
implementations allowclient-side script to interact with the user and make
dynamic pages.
Itisaninterpretedprogramminglanguage withobject-orientedcapabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java.
JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
FeaturesofJavaScript
JavaScriptisalightweight,interpretedprogramminglanguage.
InterpreterBasedScripting Language
CaseSensitive
Designedforcreatingnetwork-centric applications.
IntegratedwithHTML.
Openandcross-platform
ValidatingUser’sInput:[Link]
capability tovalidate user input for errors and also saves time. If the user leaves a
required field empty or the information is incorrect, JavaScript checks for them
before sending the data over to the server.
AdvantagesofJavaScript
Speed:Client-sideJavaScriptisveryfastbecauseitcanberunimmediately
within theclient-side browser.
Simplicity:JavaScriptis relatively simpletolearn andimplement.
Popularity:JavaScriptis usedeverywhere ontheweb.
Interoperability:JavaScriptplaysnicelywithotherlanguagesandcanbeused in a
huge variety of applications.
ServerLoad:Beingclient-sidereducesthedemandonthewebsiteserver.
Givestheabilitytocreaterichinterfaces.
Lessserverinteraction−Youcanvalidateuserinputbeforesendingthepage off
to theserver. This saves server traffic, which means less load on yourserver.
Immediatefeedbacktothevisitors
Increasedinteractivity−Youcancreateinterfacesthatreactwhenthe
userhoversover them with a mouse or activates them via the keyboard.
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
LimitationsofJavaScript
[Link] important
features –
Client-SideSecurity:Becausethecodeexecutesontheusers’computer,insomecasesitcan be
exploited for malicious purposes. This is one reason some people choose to
disableJavascript.
[Link]
security reason.
JavaScriptcannotbeusedfornetworkingapplicationsbecausethereisnosuchsupportavaila
ble.
JavaScriptdoesn'thaveanymulti-threadingormultiprocessorcapabilities.
WheretowriteJavascriptcode:
1. DirectlyinBrowser Console
2. InHTMLfile
3. InseparateJavascriptFileandlinkingthisfileinHTMLfile
ToolstorunJavaScriptCode:
JavaScriptEditors:Notepad,Notepad++,VS,Sublime,Eclipse,Atom
Browser:Chrome,Firefox,Safari,Edge
JavaScriptProgramming
Q] Explain<script>tagwithexample?
JavaScriptcan be implementedusingJavaScriptstatementsthatareplacedwithin
the<script>...</script>HTML tags in a web page.
Youcanplacethe<script>tags,containingyourJavaScript,anywherewithinyourwebpage, but it is
normally recommended that you should keep it within the<head>tags.
The<script>tagalertsthebrowserprogramtostartinterpretingallthetextbetweenthese tags as a
script. A simple syntax of your JavaScript will appear as follows.
<script
...>JavaScriptcode
</script>
Thescripttagtakestwoimportantattributes−
1. Language−[Link],its
value will be javascript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.
2. Type–Thisattributetellsthebrowserthatscriptisinplaintextandtextisorganisedin the
format of javascript.
SoyourJavaScriptsegmentwilllooklike−
<scriptlanguage="javascript"type="text/javascript">JavaScript
code
</script>
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
WhitespaceandLineBreaks
JavaScriptignoresspaces,tabs,[Link]
spaces, tabs,andnewlinesfreelyinyourprogramandyouare
freetoformatandindentyourprograms.
SemicolonsareOptional
SimplestatementsinJavaScriptaregenerallyfollowedbyasemicoloncharacter,justasthey are in C,
C++, and Java.
JavaScript,however,allowsyoutoomitthissemicolonifeachofyourstatementsareplacedon a
separate line.
Forexample,thefollowingcodecouldbewritten withoutsemicolons.
<scriptlanguage="javascript"type="text/javascript">[Link]("H
ello")
[Link]("WelcometoKhwaishAcademy")
</script>
Butwhenformattedinasinglelineasfollows,youmustusesemicolons−
<scriptlanguage="javascript"type="text/javascript">[Link]("H
ello");[Link]("WelcometoSPCAcademy")
</script>
Note−Itisagoodprogrammingpracticetousesemicolons.
CaseSensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables,
functionnames,andanyotheridentifiersmustalwaysbetypedwithaconsistentcapitalization of
letters.
SotheidentifiersTimeandTIMEwillconveydifferentmeaningsinJavaScript.
CommentsinJavaScript
JavaScriptsupports both C-styleandC++-style comments, Thus−
Anytextbetweena//andtheendofalineistreatedasacommentandisignoredbyJavaScrip
t.
Anytextbetweenthecharacters/*and*/[Link] multiple lines.
Example
ThefollowingexampleshowshowtousecommentsinJavaScript.
<scriptlanguage="javascript"type="text/javascript">
//[Link]++
/*
Thisisamulti-linecommentinJavaScript
ItisverysimilartocommentsinCProgramming
*/
</script>
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
JavaScriptEnabling
AllthemodernbrowserssuchasInternetExplorer,Firefox,chrome,andOperacomewithbuilt- in
support for JavaScript. Frequently, you may need to enable or disable this support manually.
JavaScriptinInternetExplorer
HerearesimplestepstoturnonorturnoffJavaScriptinyourInternetExplorer−
FollowTools→InternetOptionsfromthemenu.
SelectSecuritytabfromthedialogbox.
ClicktheCustomLevelbutton.
ScrolldowntillyoufindScriptingoption.
SelectEnableradiobuttonunderActivescripting.
FinallyclickOKandcomeout
JavaScriptPlacement
[Link] the
most preferred ways to include JavaScript in an HTML file are as follows −
Scriptin<head>...</head>section.
Scriptin<body>...</body>section.
Scriptin<body>...</body>and<head>...</head>sections.
Scriptinanexternalfileandthenincludein<head>...</head>section.
Inthefollowingsection,wewillseehowwecanplaceJavaScriptinanHTMLfileindifferentways.
a)JavaScriptin<head>...</head>section
Ifyouwanttohaveascriptrunonsomeevent,suchaswhenauserclickssomewhere,thenyou will place
that script in the head as follows −
<html>
<head>
<scripttype="text/javascript">functionsayHello()
{
alert("WELCOMETOHelloWorld")
}
</script>
</head>
<body>
<inputtype="button"onclick="sayHello()"value="SayHello"/>
</body>
</html>
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
a) JavaScriptin<body>...</body>section
Ifyouneedascripttorunasthepageloadssothatthescriptgeneratescontentinthepage,then the script
goes in the<body>portion of the document. In this case, you would not have any function
defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type="text/javascript">[Link]("HelloWorld")
</script>
</body>
</html>
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
b) JavaScriptin<body>and<head>Sections
YoucanputyourJavaScriptcodein<head>and<body>sectionaltogetherasfollows−
<html>
<head>
<scripttype="text/javascript">
functionsayHello()
{
alert("WelcometoHelloWorld")
}
</script>
</head>
<body>
<scripttype="text/javascript">[Link]("HelloWorld")
</script>
<inputtype="button"onclick="sayHello()"value="SayHello"/>
</body>
</html>
c) JavaScriptinExternalFile
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
AsyoubegintoworkmoreextensivelywithJavaScript,youwillbelikelytofindthatthereare cases
where you are reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag
providesamechanismtoallowyoutostoreJavaScriptinanexternalfileandthenincludeitinto your
HTML files.
HereisanexampletoshowhowyoucanincludeanexternalJavaScriptfileinyourHTMLcode using
script tag and its src attribute.
<html>
<head>
<scripttype="text/javascript"src="[Link]
%204th%20december">
</script>
</head>
<body>
<inputtype="button"onclick="sayHello()"value="SayHello"/>
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source code
inasimpletextfilewiththeextension".js"[Link], you
can keep the following content in [Link] file and then you
canuse sayHello function in your HTML file after including the [Link] file.
functionsayHello()
{
alert("WelcometoArrow")
}
[Link]("Iamcreatingjavascriptexternalcode<br>");
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
JavaScriptVariables
[Link] single
data value that can be changed later.
VariableDeclaration:
BeforeyouuseavariableinaJavaScriptprogram,youmustdeclareit. Variables are
declared with the var keyword as follows.
<scripttype="text/javascript">va
r money;
varname;
</script>
Youcanalsodeclaremultiplevariableswiththesamevarkeywordasfollows−
<scripttype="text/javascript">va
r money, name;
</script>
Avariabledeclaredwithoutavaluewillhavethevalueundefined.
VariableInitialization:
Storingavalueinavariableiscalledvariableinitialization.
Youcandovariableinitializationatthetimeofvariablecreationoratalaterpointintimewhen you
need that variable.
<scripttype="text/javascript">va
r name ="Khwaish";
varmoney;
money=2000.50;
</script>
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data
type. Unlike many other languages, you don't have to tell JavaScript during variable declaration
[Link] execution of a
program and JavaScript takes care of it automatically.
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
JavaScriptVariableScope
[Link] have
only two scopes.
GlobalVariables−Aglobalvariablehasglobalscopewhichmeansitcanbedefinedanywhere in
your JavaScript code.
Local Variables− A local variable will be visible only within a function where it is defined.
Withinthebodyofafunction,alocalvariabletakesprecedenceoveraglobalvariablewiththe same
name.
Ifyoudeclarealocalvariableorfunctionparameterwiththesamenameasaglobalvariable, you
effectively hide the global variable.
Example:
Thisproduces thefollowingresult−
Valueofais10
RulesforJavaScriptVariableNames:
1. [Link], break
or boolean variable names are not valid.
2. JavaScriptvariablenamesshouldnotstartwithanumeral(0-9).
They must begin with a letter or an underscore character.
Forexample,123testisaninvalidvariablenamebut_123testisavalidone.
3. JavaScriptvariablenamesarecase-
[Link],Nameandnamearetwodifferentvariables.
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
JavaScriptDataTypes
[Link] data
types in JavaScript.
1. Primitive datatype
2. Non-primitive (reference)datatype
1. JavaScriptprimitivedatatypes
JavaScript primitive data types are data types that refer to a single value.
[Link]:
2. JavaScriptnon-primitivedatatypes
ThedatatypesthatarederivedfromprimitivedatatypesoftheJavaScriptlanguageareknown as
non-primitive data types.
Itisalsoknownasderiveddatatypes.
Itcontainssingle ormultiple key-valuepair/s.
Thenon-primitivedatatypesareasfollows:
- Object
- Array
- RegExp
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
1.3Objects
RealLifeObjects,Properties,andMethods
Inreallife,acarisanobject.
Acarhaspropertieslikeweightandcolor,andmethodslikestartandstop:
[Link]=Fiat [Link]()
[Link]=500 [Link]()
[Link]=850kg [Link]()
[Link]=white [Link]()
A] JavaScriptObjects
Apropertyisavalueorsetofvaluesthatisamemberofanobject
Amethodisafunctionthatisamemberofanobject.
ObjectsinJavaScriptmaybedefinedas,anunorderedcollectionofrelateddataof
primitive or reference typesin the form of"key: value"pairs,
Youaccessanobject'spropertiesandmethodsbyusingthedotsyntaxalongwiththe
objectnameanditspropertyormethod.
B] ObjectName
EachobjectisuniquelyidentifiedbyanameorID.
Awebpagecontainsmanyobjects,[Link] can be
easily distinguishable by using its name or ID.
C] Property
Apropertyisadataorvalueassociatedwithanobject.
Objectscanhavemanydata'sassociatedwiththemdependingonapplicationofuse.
Forexample,aformobjectcanhaveatitle,awidthandaheightaspropertieswhereasa window object
can have a background color, a width and height as properties.
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
Hence,[Link]
brackets{...}withlistofproperties.
Apropertyisa"key:valuepair,wherekeyisastring(alsocalleda"propertyname"),and value
can be anything.
D] CreatingaJavaScriptObject
WithJavaScript,[Link] new
objects:
Defineandcreateasingleobject,usinganobjectliteral.
Defineandcreateasingleobject,withthekeywordnew.
Defineanobjectconstructor,andthencreateobjectsoftheconstructedtype.
1. UsinganObjectLiteral
[Link],youbothdefineand create an
object in one statement. An object literal is a list ofname:value pairs inside curly braces {}.
2. UsingtheJavaScript Keywordnew
Syntax:
varobjectname=newObject();
Here,newkeywordisusedtocreateobject.
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
Example:
<script>
varemp=newObject();
[Link]=101;
[Link]=”Khwaish";
[Link]=50000;
[Link]([Link]+""+[Link]+""+[Link]);
</script>
3. ByusinganObjectconstructor
Here,[Link] current
object by using this keyword.
Thethiskeywordreferstothecurrentobject.
Example:
<script>
functionemp(id,name,salary)
{
[Link]=id;
[Link]=name;
[Link]=salary;
}
e=new emp(103,"Khwaish
Shahani",30000);[Link]([Link]+""+[Link]+""+e.s
alary);
</script>
E] DotSyntax:
Theproperties&methodsassociatedwithanyobjectcanbeaccessedbyusingtheobject name
with dot syntax.
E.g. [Link], [Link]&[Link]().
Inthefollowingcodeuserobjectiscreatedwithtwoproperties:
1Thefirstpropertyhasthenamefnameandthevalue"Computer"
[Link]"Engineering".
Youcanaccesstheobjectpropertiesinfollowingtwoways:
1. [Link];
2. user[“fname”]
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
Example:
Output:
F] Method
Amethodisasetofstatements(actions)performedbyanobjectwhenitreceivesamessage.
OnaformwhenyouclickonSubmitbutton,theformissubmittedtoserversideapplication. Here
Submit is an object, and clicking on it causes the button to process a method.
Example:
<script>
varperson={
firstName:"John",
lastName :"Doe",
fullName:function()
{
[Link]+""+[Link];
}
};
[Link](“UserNameis:”+[Link]());
</script>
ThethisKeyword
Inafunctiondefinition,thisreferstothe"owner"ofthefunction.
Intheexampleabove,thisisthepersonobjectthat"owns"thefullNamefunction. In
other words,[Link] thefirstNameproperty ofthis object.
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
1.5JavaScriptOperator
JavaScriptoperatorsaresymbolsthatareusedtoperformoperationsonoperands.
JavaScript supports the following types of operators.
ArithmeticOperators
ComparisonOperators
Logical(orRelational)Operators
AssignmentOperators
Conditional (or ternary) Operators
Letshavealookonalloperatorsonebyone.
1)ArithmeticOperators
Arithmeticoperatorsareusedtoperformarithmeticoperationsontheoperands. Assume
variable A holds 10 and variable B holds 20, then −
Sr. Operator&Description Example
1 +(Addition):Addstwooperands Ex:A+Bwillgive30
4 /(Division):Dividethenumeratorbythedenominator Ex:B/Awillgive2
5 %(Modulus):Outputstheremainderofanintegerdivision Ex:B%Awillgive0
6 ++(Increment):Increasesanintegervaluebyone Ex:A++willgive11
7 --(Decrement):Decreasesanintegervaluebyone Ex:A--willgive9
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
2)AssignmentOperators
JavaScriptsupports thefollowingassignmentoperators−
Sr. Operator&Description Example
=(Simple Assignment)
Ex:C=A+Bwillassig the n
1 Assignsvaluesfromtherightsideoperandtotheleftsideoperand
value of A + B into C
+=(AddandAssignment)
Ex:C+=Aisequivalentt C
2 Itaddstherightoperandtotheleftoperandandassignsthe result to
=C+A
the left operand.
−=(SubtractandAssignment)
Ex:C-=Aisequivalentt C
3 Itsubtractstherightoperandfromtheleftoperandand assigns the
=C - A
result to the left operand.
*=(MultiplyandAssignment)
Ex:C*=Aisequivalentt C
4 Itmultipliestherightoperandwiththeleftoperandand assigns the
=C*A
result to the left operand.
/=(DivideandAssignment)
Ex:C/=Aisequivalentt C
5 Itdividestheleftoperandwiththerightoperandandassigns the
=C/A
result to the left operand.
%=(ModulesandAssignment)
Ex:C%=Aisequivalen to t
6 Ittakesmodulususingtwooperandsandassignstheresultto the
C=C%A
left operand.
Ex.C**=AisequivalenttoC
7 **=
=C*A
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
3)ComparisonOperators
JavaScript supports the following comparison operators −
AssumevariableAholds10andvariableBholds20,then−
Sr. Operator&Description Example
==(Equal)
1 Checksifthevalueoftwooperandsareequalornot,ifyes,thenthe Ex:(A==B)isnottru .
condition becomes true.
!=(NotEqual)
2 Checksifthevalueoftwooperandsareequalornot,ifthevalues are not Ex:(A!=B)istrue.
equal, then the condition becomes true.
>(Greaterthan)
3 Checksifthevalueoftheleftoperandisgreaterthanthevalueof the Ex:(A>B)isnottrue .
right operand, if yes, then the condition becomes true.
<(Lessthan)
4 Checksifthevalueoftheleftoperandislessthanthevalueofthe right Ex:(A<B)istrue.
operand, if yes, then the condition becomes true.
>=(GreaterthanorEqualto)
5 Checksifthevalueoftheleftoperandisgreaterthanorequaltothe value of Ex:(A>=B)isnottru .
the right operand, if yes, then the condition becomes true.
<=(LessthanorEqualto)
6 Checksifthevalueoftheleftoperandislessthanorequaltothe value of the Ex:(A<=B)istrue.
right operand, if yes, then the condition becomes true.
Ex:A=5andB=”5”
7 === (equalvalueandequaltype)
ThenA===BisFalse
Ex:A=5andB=”5”
8 !== (NotequalvalueorNotequaltype)
ThenA!==BisTrue
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
4) LogicalOperators
AssumevariableAholds10,variableBholds20,variableCholds30,then−
&&(LogicalAND)
Ex:(A<B&&B<C) istrue.
1 Ifboththeoperandsaretrue,thentheconditionbecomes true,
otherwise it returns false.
||(LogicalOR)
2 Ifanyofitsargumentsaretrue,itreturnstrue,otherwiseit returns Ex:(A>B||B<C)isfalse.
false.
!(LogicalNOT)
3 Ifaconditionistrue,thentheLogicalNOToperatorwill make it Ex:!(A&&B)isfalse.
false and vice versa.
5) BitwiseOperators
AssumevariableAholds2andvariableBholds3,then−
Sr. Operator&Description Example
&(BitwiseAND)
1 It performs a Boolean AND operation on each bit of its Ex:(A&B)is2.
integerarguments.
|(BitWiseOR)
2 It performs a Boolean OR operationon each bit of its integerarguments. Ex:(A|B)is3.
^(BitwiseXOR)
It performs a Boolean exclusive ORoperation on each bit of its integer
3 Ex:(A^B)is1.
arguments. Exclusive OR means that either operand one is true or
operand two is true, but not both.
~(BitwiseNot)
4 Itisaunaryoperatorandoperatesbyreversingallthebitsintheoperand. Ex:(~B)is-4.
<<(LeftShift)
Itmovesallthebitsinitsfirstoperandtotheleftbythenumber places
5 specified in the second operand. New bits are filled with zeros. Shifting Ex:(A<<1)is4.
avalue leftby oneposition isequivalentto multiplyingit by2, shifting two
positions is equivalent to multiplying by 4, and so on.
>>(RightShift)
6 [Link]’svalueismovedrightby the Ex:(A>>1)is1.
number of bits specified by the right operand.
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
6)TernaryOperator
JavaScriptincludesspecialoperatorcalledternaryoperator:?thatassignsavaluetoavariable based
on some condition. This is like short form of if-else condition.
Syntax:
<condition>?<value1>:<value2>;
Ternaryoperatorstartswith conditional expressionfollowedby?[Link] (after
?andbefore:operator)[Link] false then
third part (after :) will be executed.
Example:
vara=10,b=5;
varc=a>b?a:b;//valueofcwouldbe10 vard
=a>b?b :a; // valueofd wouldbe 5
ConditionalStatements
Whilewritingaprogram,theremaybeasituationwhenyouneedtoadoptoneoutofagivenset
[Link],youneedtouseconditionalstatementsthatallowyourprogramtomake correct
decisions and perform right actions.
JavaScriptsupportsconditionalstatementswhichareusedtoperformdifferentactionsbased on
different conditions.
A] if..elsestatement
FlowChartofif-else
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
1) ifstatement
TheifstatementisthefundamentalcontrolstatementthatallowsJavaScripttomakedecisions and
execute statements conditionally.
Syntax
if(expression)
{
Statement(s)tobeexecutedifexpressionistrue
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
[Link],[Link], you will
use comparison operators while making decisions.
Example
Trythefollowingexampletounderstandhowtheifstatementworks.
<html>
<body>
<scripttype="text/javascript">varage=20;if(age>18
)
{
[Link]("Qualifiesfordriving");
}
</script>
</body>
</html>
Output
2) if...elsestatement
Syntax
if(expression)
{
Statement(s)tobeexecutedifexpressionistrue
}
else
{
Statement(s)tobeexecutedifexpressionisfalse
}
ClientSideScripting(Unit1)
BasicsofJavaScriptProgramming
[Link],thegivenstatement(s)in the ‘if’
block, are executed. If the expression is false, then the given statement(s) in the else block are
executed.
ClientSideScripting(Unit1)
Example
Trythefollowingcodetolearnhowtoimplementanif-elsestatementinJavaScript.
<html>
<body>
<scripttype="text/javascript">varage=15;
if(age>18)
{
[Link]("<b>Qualifiesfordriving</b>");
}
else
{
[Link]("<b>Doesnotqualifyfordriving</b>");
}
</script>
</body>
</html>
Output
3) if...elseif...statement
Theif...elseif...statementisanadvancedformofif…elsethatallowsJavaScripttomakeacorrect
decision out of several conditions.
Syntax
Thesyntaxofanif-else-ifstatementisasfollows−
if(expression1)
{
Statement(s)tobeexecutedifexpression1istrue
}
elseif(expression2)
{
Statement(s)tobeexecutedifexpression2istrue
}
elseif(expression3)
{
Statement(s)tobeexecutedifexpression3istrue
}
else
{
Statement(s)tobeexecutedifnoexpressionistrue
}
ClientSideScripting(Unit1)
Example
Itisjustaseriesofifstatements,whereeachifisapartoftheelseclauseoftheprevious statement.
Statement(s) are executed based on the true condition, if none of the conditions is
true,thentheelseblockisexecuted.
ClientSideScripting(Unit1)
Example
Trythefollowingcodetolearnhowtoimplementanif-else-ifstatementinJavaScript.
<!DOCTYPEhtml>
<html>
<head>
<title>FirstPage</title>
<scripttype="text/javascript">varm1
=30,m2=40,m3=35,m4=34,m5=30;
vartotal=m1+m2+m3+m4+m5;varper=total/5
[Link]("Totalis"+total)[Link]("<br>")[Link]("Percentageis"+per)documen
[Link]("<br>")
if(per>70)
{
[Link]("Distinction")
}
elseif(per>60)
{
[Link]("FirstClass")
}
elseif(per>50)
{
[Link]("SecondClass")
}
elseif(per>40)
{
[Link]("Pass")
}
else
{
[Link]("Fail")
}
</script>
</head>
<body>
</body>
</html>
ClientSideScripting(Unit1)
4) nestedifelsestatement
[Link]:
if(condition1)
{
//Executeswhencondition1istrue if
(condition2)
{
//Executeswhencondition2istrue
}
}
Example:
<!DOCTYPEhtml>
<html>
<head>
<title>Nested IfElse</title>
<scripttype="text/javascript">
vara=10,b=40,c=30;
if(a>b)
{
if(a>c)
{
[Link]("Largestnumberis"+a)
}
else
{
[Link]("largest numberis"+c)
}
}
else
{
if(b>c)
{
[Link]("Largestnumberis"+b)
}
else
{
[Link]("Largestnumberis"+c)
}
}
</script>
</head>
<body>
</body>
</html>
ClientSideScripting(Unit1)
Input:
<!DOCTYPEhtml>
<html>
<head>
<title>Nested
If
Else</title>
<scripttype="text/javasc
ript">vara=10,b=40,c=30;
if(a>b)
{
if(a<c)
{
[Link]("LargestN
umber Is"+a)
}
else
{
[Link]("LargestN
umber Is"+c)
}
}
else
{
if(b>c){[Link]("
LargestNumber is"+b)
}
else{[Link]("Lar
gestNumber is"+c)
}
}
</script>
</head>
<body>
</body>
</html>
Output:
ClientSideScripting(Unit1)
B) switchstatement
TheJavaScriptswitchstatementisusedindecisionmaking.
Theswitchstatementevaluatesanexpressionandexecutesthecorrespondingbodythat matches
the expression's result.
Syntax:
switch(variable/expression)
{
casevalue1:
//bodyofcase1break;
casevalue2:
//bodyofcase2break;
casevalueN:
//bodyofcaseNbreak;
default:
//bodyofdefault
}
Theswitchstatementevaluatesavariable/expression insideparentheses().
Iftheresultoftheexpressionisequaltovalue1,itsbodyisexecuted.
Iftheresultoftheexpressionisequaltovalue2,itsbodyisexecuted.
[Link],thedefaultbodyexecutes.
Notes:
[Link],theswitchstatementends.
Ifthebreakstatementisnotused,thecasesafterthematchingcasearealsoexecuted.
Thedefaultclauseisalsooptional.
Flowchart:
ClientSideScripting(Unit1)
Example:
<html>
<body>
<scripttype="text/javascript">var grade ='d';
[Link]("Enteringswitchblock<br/>");switch(grade){case'A':d
[Link]("Good job<br />");break;
case'B':[Link]("Prettygood<br/>");break;case
'C':[Link]("Passed<br
/>");break;case'D':[Link]("Notsogood<br/>");
break;case'E':[Link]("Failed<br
/>");break;default:[Link]("Unknown grade<br
/>")
}
[Link]("Exitingswitchblock");
</script>
</body>
</html>
Output
Enteringswitchblock Good
job
Exitingswitchblock
ClientSideScripting(Unit1)
Example2
<!DOCTYPE html>
<html>
<head>
<title>Switch</title>
<scripttype="text/javascript">
var operator='+';
var number1=23,number2=10,result;[Link]("Enteringswitchblock<br/>");
switch(operator)
{
case'+':
result=number1+number2;[Link](result)break;
case'-':
result=number1-number2;[Link](result)break;
case'*':
result=number1*number2;[Link](result)
break;case'/':
result=number1/number2;[Link](result)
break;case'%':
result =number1%number2;[Link](result)
break;
default:
[Link]("WrongArithmeticOperator")break;
}
</script>
</head>
<body>
</body>
</html>
<!DOCTYPEhtml>
<html>
<head>
<title>Switch</title>
<scripttype="text/javascript">
varoperator='+';
var
number1=23,number2=10,result;[Link]("Entering
switch block<br />");
switch(operator)
{
case'+':
result=number1+number2;d
[Link](result)break;
case'-':
result=number1-
number2;[Link](re
sult) break;
ClientSideScripting(Unit1)
case'*':
result=number1*number2;[Link](result)
break;
case'/':
result=number1/number2;[Link](result)
break;
case'%':
result=number1%number2;[Link](result)
break;
default:
[Link]("WrongArithmeticOperator")
break;
}
</script>
</head>
<body>
</body>
</html>
OUTPUT:
ClientSideScripting(Unit1)
LoopinJavaScript
While writing a program, you may encounter a situation where you need to perform an action
[Link],youwouldneedtowriteloopstatementstoreducethe number
of lines.
1) ThewhileLoop
Thepurposeofawhileloopistoexecuteastatementorcodeblockrepeatedlyaslongas an expression
is true. Once the expression becomes false, the loop terminates.
Syntax:
while(expression)
{
Statement(s)tobeexecuted ifexpressionistrue
}
Awhileloopevaluatestheconditioninsidetheparenthesis().
Iftheconditionevaluatestotrue,thecodeinsidethewhileloopisexecuted.
Thecondition isevaluatedagain.
Thisprocesscontinuesuntiltheconditionisfalse.
Whentheconditionevaluatestofalse,theloopstops.
FlowChart
ClientSideScripting(Unit1)
Example:
<html>
<body>
<scripttype="text/javascript">varcount=0;[Link]("Starting
Loop");
while(count<10){
[Link]("CurrentCount:"+count+"<br/>");count++;
}
[Link]("Loopstopped!");
</script>
<p>Setthevariabletodifferentvalueandthentry...</p>
</body>
</html>
Output
Starting Loop
Current Count: 0
Current Count: 1
Current Count: 2
Current Count: 3
ClientSideScripting(Unit1)
Current Count: 4
Current Count: 5
Current Count: 6
Current Count: 7
Current Count: 8
Current Count: 9
Loopstopped!
Setthevariabletodifferentvalueandthentry...
ClientSideScripting(Unit1)
2) Thedo...whileLoop
Thedo...whileloopissimilartothewhileloopexceptthattheconditioncheckhappensatthe
[Link],evenifthe condition is false.
FlowChart
Syntax
do
{
Statement(s)tobeexecuted;
}while(expression);
Note−Don’tmissthesemicolonusedattheendofthedo...whileloop.
Example:
Trythefollowingexampletolearnhowtoimplementado-whileloopinJavaScript.
<html>
<body>
<scripttype="text/javascript">
<!--
varcount=0;
[Link]("StartingLoop"+"<br/>");do{[Link]("CurrentC
ount:"+count+"<br
/>");
count++;
}
while(count<5);
[Link]("Loopstopped!");
//-->
</script>
<p>Setthevariabletodifferentvalueandthentry...</p>
</body>
ClientSideScripting(Unit1)
</script>
<p>Setthevariabletodifferentvalueandthentry...</p>
</body>
</html>
Output
StartingLoop
Current Count: 0
Current Count: 1
Current Count: 2
Current Count: 3
Current Count: 4
LoopStopped!
Setthevariabletodifferentvalueandthentry...
3) The'for'loop
The'for'[Link] parts −
[Link]
initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition is
true,thenthecodegiveninsidetheloopwillbeexecuted,otherwisethecontrolwillcome out of
the loop.
Theiterationstatementwhereyoucanincreaseordecreaseyourcounter. You
can put all the three parts in a single line separated by semicolons.
FlowChart
ClientSideScripting(Unit1)
Syntax
for(initialization;testcondition;iterationstatement)
{
Statement(s)tobeexecutediftestconditionistrue
}
ClientSideScripting(Unit1)
Example
<html>
<body>
<scripttype="text/javascript">
<!--
varcount=0;
[Link]("StartingLoop"+"<br/>");do{[Link]("CurrentC
ount:"+count+"<br
/>");
count++;
}
while(count<5);
[Link]("Loopstopped!");
//-->
</script>
<p>Setthevariabletodifferentvalueandthentry...</p>
</body>
</html>
Output
Starting Loop
CurrentCount:0
CurrentCount:1
CurrentCount:2
CurrentCount:3
CurrentCount:4
CurrentCount:5
CurrentCount:6
CurrentCount:7
CurrentCount:8
CurrentCount:9 Loop
stopped!
Setthevariabletodifferentvalueandthentry...
ClientSideScripting(Unit1)
breakstatement
The break statement is used to terminate from the loop immediately. When a break statement is
encounteredinsidealoop,theloopiterationstopsthere,andcontrolreturnsfromtheloop immediately to
the first statement after the loop.
Example:
<script
type="text/javascript">var
count;
[Link]("StartingLoop"+"<br/>");
for(count = 0; count<10; count++)
{
if(count==5)
{
break
}
[Link]("CurrentCount:"+count);
[Link]("<br />");
}
</script>
Output:
Starting Loop
CurrentCount:0
CurrentCount:1
CurrentCount:2
CurrentCount:3
CurrentCount:4
continuestatement
ThecontinuestatementinJavaisusedtoskipthecurrentiterationofaloop.
<script
type="text/javascript">var
count;
[Link]("Starting Loop"+"<br/>");
for(count=0;count<10;count++)
{
if(count==5)
{
continue
}
[Link]("CurrentCount:"+count);
[Link]("<br />");
ClientSideScripting(Unit1)
</script>
ClientSideScripting(Unit1)