Javascript - Variables, If..

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

JSVariables,If...

Else,Switch
Note:manyofthecontentsofthispagearetakenfromw3schoolwebsite.

Variables
Variablesareusedtostoredata.Example:
<scripttype="text/javascript">
varname="Hege"
document.write(name)
document.write("<h1>"+name+"</h1>")
</script>

Avariableisa"container"forinformationyouwanttostore.Avariable'svaluecanchangeduringthe
script.Youcanrefertoavariablebynametoseeitsvalueortochangeitsvalue.

Rulesforvariablenames:

Variablenamesarecasesensitive
Theymustbeginwithaletterortheunderscorecharacter

DeclareaVariable

Youcancreateavariablewiththevarstatement:
varstrname=somevalue

Youcanalsocreateavariablewithoutthevarstatement:
strname=somevalue

AssignaValuetoaVariable

Youcanassignavaluetoavariablelikethis:
varstrname="Hege"

Orlikethis:
strname="Hege"

Thevariablenameisontheleftsideoftheexpressionandthevalueyouwanttoassigntothevariableis
ontheright.Nowthevariable"strname"hasthevalue"Hege".

LifetimeofVariables

Whenyoudeclareavariablewithinafunction,thevariablecanonlybeaccessedwithinthatfunction.
Whenyouexitthefunction,thevariableisdestroyed.Thesevariablesarecalledlocalvariables.Youcan
havelocalvariableswiththesamenameindifferentfunctions,becauseeachisrecognizedonlybythe
functioninwhichitisdeclared.

Ifyoudeclareavariableoutsideafunction,allthefunctionsonyourpagecanaccessit.Thelifetimeof
thesevariablesstartswhentheyaredeclared,andendswhenthepageisclosed.

If...Else
Thefollowingisanexampleofusingifstatement:
<scripttype="text/javascript">
vard=newDate()
vartime=d.getHours()
if(time<10)
{
document.write("<strong>Goodmorning</strong>")
}
</script>

ConditionalStatements
Veryoftenwhenyouwritecode,youwanttoperformdifferentactionsfordifferentdecisions.Youcan
useconditionalstatementsinyourcodetodothis.

InJavaScriptwehavethefollowingconditionalstatements:

ifstatementusethisstatementifyouwanttoexecutesomecodeonlyifaspecifiedconditionis
true
if...elsestatementusethisstatementifyouwanttoexecutesomecodeiftheconditionistrueand
anothercodeiftheconditionisfalse
if...elseif....elsestatementusethisstatementifyouwanttoselectoneofmanyblocksofcodeto
beexecuted
switchstatementusethisstatementifyouwanttoselectoneofmanyblocksofcodetobe
executed

IfStatement

Youshouldusetheifstatementifyouwanttoexecutesomecodeonlyifaspecifiedconditionistrue.

Syntax:
if(condition)
{
codetobeexecutedifconditionistrue
}

Notethatifiswritteninlowercaseletters.Usinguppercaseletters(IF)willgenerateaJavaScripterror!
<scripttype="text/javascript">
//Write"Lunchtime!"ifthetimeis11
vard=newDate()
vartime=d.getHours()
if(time==11)
{document.write("<em>Lunchtime!</em>")}
</script>

Note:Whencomparingvariablesyoumustalwaysusetwoequalssignsnexttoeachother(==)!

If...elseStatement
Ifyouwanttoexecutesomecodeifaconditionistrueandanothercodeiftheconditionisnottrue,use
theif....elsestatement.

Syntax:
if(condition)
{
codetobeexecutedifconditionistrue
}
else
{
codetobeexecutedifconditionisnottrue
}

Example
<scripttype="text/javascript">
//Ifthetimeislessthan10,
//youwillgeta"Goodmorning"greeting.
//Otherwiseyouwillgeta"Goodday"greeting.
vard=newDate()
vartime=d.getHours()
if(time<10)
{
document.write("Goodmorning!")
}
else
{
document.write("Goodday!")
}
</script>

If...elseif...elseStatement

Youshouldusetheif....elseif...elsestatementifyouwanttoselectoneofmanysetsoflinestoexecute.

Syntax:
if(condition1)
{
codetobeexecutedifcondition1istrue
}
elseif(condition2)
{
codetobeexecutedifcondition2istrue
}
else
{
codetobeexecutedifcondition1and
condition2arenottrue
}

Example
<scripttype="text/javascript">
vard=newDate()
vartime=d.getHours()
if(time<10)
{
document.write("<b>Goodmorning</b>")
}
elseif(time>10&&time<16)
{
document.write("<b>Goodday</b>")
}
else
{
document.write("<b>HelloWorld!</b>")
}
</script>

Switch
Youshouldusetheswitchstatementifyouwanttoselectoneofmanyblocksofcodetobeexecuted.

Syntax:
switch(n)
{
case1:
executecodeblock1
break
case2:
executecodeblock2
break
default:
codetobeexecutedifnis
differentfromcase1and2
}

Thisishowitworks:Firstwehaveasingleexpressionn(mostoftenavariable),thatisevaluatedonce.
Thevalueoftheexpressionisthencomparedwiththevaluesforeachcaseinthestructure.Ifthereisa
match,theblockofcodeassociatedwiththatcaseisexecuted.Usebreaktopreventthecodefrom
runningintothenextcaseautomatically.

Example
<scripttype="text/javascript">
//Youwillreceiveadifferentgreetingbased
//onwhatdayitis.NotethatSunday=0,
//Monday=1,Tuesday=2,etc.
vard=newDate()
theDay=d.getDay()
switch(theDay)
{
case5:
document.write("FinallyFriday")
break
case6:
document.write("SuperSaturday")
break
case0:
document.write("SleepySunday")
break
default:
document.write("I'mlookingforwardtothisweekend!")
}
</script>

2007MehmudAbliz

You might also like