Belajar Javascript : if…else Statement

posted in: Tutorial Pemrograman | 0

if statement

Pernyataan if adalah pernyataan kontrol mendasar yang memungkinkan JavaScript untuk membuat keputusan dan melaksanakan pernyataan kondisional.

Syntax

Sintaks untuk dasar pernyataan if adalah sebagai berikut –


if (expression){

Statement(s) to be executed if expression is true

}

if…else statement:

Syntax


if (expression){
 Statement(s) to be executed if expression is true
}

else{
 Statement(s) to be executed if expression is false
}

if…else if… statement

Syntax

Sintaks pernyataan if-else-if adalah sebagai berikut


if (expression 1){
Statement(s) to be executed if expression 1 is true
}

else if (expression 2){
Statement(s) to be executed if expression 2 is true
}

else if (expression 3){
Statement(s) to be executed if expression 3 is true
}

else{
Statement(s) to be executed if no expression is true
}

Contoh

<html>
<body>

<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}

else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}

else if( book == "economics" ){
document.write("<b>Economics Book</b>");
}

else{
document.write("<b>Unknown Book</b>");
}
//-->
</script>

<p>Set the variable to different value and then try...</p>
</body>
<html>

 

Leave a Reply