Professional Documents
Culture Documents
1/17
2/17
WE WILL LOOK AT
if
if ... else
default
3/17
MAKING DECISIONS
if is used similar to regular English
Lots of variations e.g.
if
if ... else
if ... elseif ... else
if ... elseif ... elseif ... else
4/17
COMPARING THINGS
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
5/17
EXAMPLE
<!doctypehtml>
<html>
<head><script>
varuser_name
user_name=prompt("Whatisyourname?")
if(user_name=="dave")
alert("Greatname!")
</script></head>
</html>
6/17
USING BRACES
You must use braces { } for more than 1 line of code:
if(user_name=="dave"){
alert("Greatname!")
awesome_name=true
}
7/17
IF ... ELSE
else goes at the end of the if
It handles any situation not
already handled at that point
8/17
<!doctypehtml>
<html>
<head><script>
varuser_name
user_name=prompt("Whatisyourname?")
if(user_name=="dave")
alert("Greatname!")
else
alert("Yournameisn'tgreat...")
</script></head>
</html>
9/17
IF ... ELSE IF
Use elseif to add another test
You can do this as many times as you like
10/17
<!doctypehtml>
<html>
<head><script>
varuser_name
user_name=prompt("Whatisyourname?")
if(user_name=="dave")
alert("Greatname!")
elseif(user_name=="jogesh")
alert("Prettygoodname!")
</script></head>
</html>
11/17
12/17
<!doctypehtml>
<html><head><script>
varuser_name
user_name=prompt("Whatisyourname?")
if(user_name=="dave")
alert("Greatname!")
elseif(user_name=="jogesh")
alert("Prettygoodname!")
elseif(user_name=="oz")
alert("Excellentname!")
else
alert("Yournameisn'tgreat,nevermind...")
</script></head></html>
13/17
SWITCH
Used for a series of comparisons:
switch(variable_name){
case"option_1":do_something_1()
break
...:...
case"option_n":do_something_n()
break
default:do_something_default()
}
14/17
<!doctypehtml>
<html>
<head>
<script>
varuser_name=prompt("Whatisyourname?")
switch(user_name){
case"dave":
alert("Greatname!")
break
case"jogesh":
alert("Prettygoodname!")
break
default:
alert("Yournameisn'tgreat,nevermind...")
}
</script>
</head>
</html>
15/17
SWITCH
break is used to stop any more case comparisons
Sometimes break is appropriate, sometimes it isn't
16/17
<!doctypehtml>
<html>
<head>
<script>
varuser_name=prompt("Whatcountrywouldyouliketovisit?")
switch(user_name){
case"Canada":
case"France":
alert("Takemealso!")
break
case"Japan":
case"Philippines":
alert("Great!Havefun!")
break
case"NorthKorea":
alert("Oh!Goodluck!")
break
default:
alert("Iamsureyouwillhaveagreattime")
}
</script>
</head>
</html>
17/17