CIS 375Web App Dev II Java Script II
CIS 375—Web App Dev II Java. Script II
if and if…else Syntax if (condition) { code to be executed if condition is true } else { code to be executed if condition is true } 2
Example of if Statement // Display “Good morning” if before 10 am var today = new Date() var time = today. get. Hours() if (time < 10) { document. write("<b>Good morning</b>") } 3
Example of if…else Statement // Display “Good morning” if before 10 am // Display “Good day!” otherwise var today = new Date() var time = today. get. Hours() if (time < 10) { document. write("<b>Good morning</b>") } else { document. write("Good day!") } 4
Syntax of switch Statement switch (expression) { case label 1: code to be executed if expression = label 1 break case label 2: code to be executed if expression = label 2 break default: code to be executed if expression is different from both label 1 and label 2 } 5
Example of switch Statement var today = new Date() the. Day = today. get. Day() switch (the. Day) { case 5: document. write("Finally Friday") break case 6: document. write("Super Saturday") break case 0: document. write("Sleepy Sunday") break default: document. write(“Can’t wait till the weekend!”) } 6
Syntax for Looping n while (condition) { code to be executed } n do…while do { code to be executed } while (condition) n for (equivalent to _______ with a counter variable) for (initialization; condition; increment) { code to be executed } 7
Examples of while & do…while n while i = 0 while (i <= 5){ document. write("The number is " + i) document. write(" ") i++ } n do…while i = 0 do{ document. write("The number is " + i) document. write(" ") i++ } while (i <= 5) 8
Example of for Loop for (i = 1; i <= 6; i++){ document. write("<h" +i+ ">This is header " + i) document. write("</h" + i + ">") } 9
Miscellaneous Guidelines n Java. Script is ______ sensitive n n White space (use to make code more ______) n n n Java. Script ignores extra spaces name="Hege" same as name = "Hege“ Use the “” to insert special characters n n A function named "myfunction" is not the same as "my. Function". document. write (“Let’s sing "Happy Birthday". ") Comments n Use // for single line, /* comments */ for a block 10
- Slides: 10