SlideShare ist ein Scribd-Unternehmen logo
1 von 47
JavaScript, Sixth Edition
Chapter 3
Building Arrays and Controlling Flow
JavaScript, Sixth Edition 2
Objectives
In this chapter, you will:
• Store data in arrays
• Use while statements, do/while statements, and
for statements to repeatedly execute code
• Use continue statements to restart looping
statements
• Use if statements, if/else statements, and
switch statements to make decisions
• Nest one if statement in another
JavaScript, Sixth Edition 3
Storing Data in Arrays
• Array
– Set of data represented by a single variable name
Figure 3-1 Conceptual illustration of an array
JavaScript, Sixth Edition 4
Declaring and Initializing Arrays
• Array literal
– most common way to create an array
– declares a variable and specifies array as content
• Syntax
var name = [value1, value2, value3, …];
• Example:
– Create an array named newsSections containing 4
strings as elements
var newsSections = ["world","local","opinion","sports"]
JavaScript, Sixth Edition 5
Declaring and Initializing Arrays
(cont’d.)
• Element
– Each piece of data contained in an array
• Index
– Element’s numeric position within the array
– Array element numbering
• Starts with index number of zero (0)
• Reference element using its index number
– Example: to reference the 2nd
element in the
newsSections array
newsSections[1]
JavaScript, Sixth Edition 6
Declaring and Initializing Arrays
(cont’d.)
• Assigning values to individual array elements
– Include the array index for an individual element
• Example:
– Add value "entertainment" as fifth element of
newsSections array
newsSections[4] = "entertainment";
JavaScript, Sixth Edition 7
Declaring and Initializing Arrays
(cont’d.)
• Can create an array without any elements
– Add new elements as necessary
– Array size can change dynamically
var colors = [];
colors[2] = "yellow";
• JavaScript values assigned to array elements
– Can be different data types
JavaScript, Sixth Edition 8
Accessing Element Information
• To access an element’s value:
– Include brackets and element index
• Examples:
var sec1Head = document.getElementById("section1");
var sec2Head = document.getElementById("section2");
var sec3Head = document.getElementById("section3");
sec1Head.innerHTML = newsSections[0]; // "world"
sec2Head.innerHTML = newsSections[1]; // "local"
JavaScript, Sixth Edition 9
Modifying Elements
• To modify values in existing array elements
– Include brackets and element index
• Can change a value assigned to an array element
• Example:
newsSections[4] = "living";
JavaScript, Sixth Edition 10
Determining the Number of Elements in
an Array
• length property
– Returns the number of elements in an array
• Syntax
name.length;
JavaScript, Sixth Edition 11
Using the Array Object
• JavaScript represents arrays with the Array object
– Contains a special constructor named Array()
• Constructor
– Special function type used as the basis for creating
reference variables
• Syntax
var newsSections = new Array(6);
• Array literals preferred
– Easier
JavaScript, Sixth Edition 12
Referencing Default Collections of
Elements
• getElementsByTagName() method
– Can reference web page element by looking up all
elements of a certain type in document and
referencing one element in that collection
– Resulting collection uses syntax similar to arrays
• Example:
document.getElementsByTagName("li")[2]
JavaScript, Sixth Edition 13
Repeating Code
• Loop statement
– Control flow statement repeatedly executing a
statement or a series of statements
• While a specific condition is true or until a specific
condition becomes true
• Three types of loop statements
– while statements
– do/while statements
– for statements
JavaScript, Sixth Edition 14
while Statements
• while statement
– Repeats a statement or series of statements
• As long as a given conditional expression evaluates to
a truthy value
• Syntax
while (expression) {
statements
}
• Iteration
– Each repetition of a looping statement
JavaScript, Sixth Edition 15
while Statements (cont’d.)
• Counter
– Variable incremented or decremented with each loop
statement iteration
• Examples:
– while statement using an increment operator
– while statement using a decrement operator
– while statement using the *= assignment operator
JavaScript, Sixth Edition 16
var count = 1;
while (count <= 5) {
document.write(count + "<br />");
count++;
}
document.write("<p>You have printed 5 numbers.</p>");
while Statements (cont’d.)
Result in browser:
JavaScript, Sixth Edition 17
var count = 10;
while (count > 0) {
document.write(count + "<br />");
count--;
}
document.write("<p>We have liftoff.</p>");
while Statements (cont’d.)
Result in browser:
JavaScript, Sixth Edition 18
var count = 1;
while (count <= 100) {
document.write(count + "<br />");
count *= 2;
}
while Statements (cont’d.)
Result in browser:
JavaScript, Sixth Edition 19
while Statements (cont’d.)
• Infinite loop
– Loop statement that never ends
• Conditional expression: never false
– Example:
var count = 1;
while (count <= 10) {
window.alert("The number is " + count + ".");
}
JavaScript, Sixth Edition 20
while Statements (cont’d.)
• Example:
– assigning array element values to table cells:
function addColumnHeaders() {
var i = 0;
while (i < 7) {
document.getElementsByTagName("th")↵
[i].innerHTML = daysOfWeek[i];
i++;
}
}
JavaScript, Sixth Edition 21
do/while Statements
• do/while statement
– Executes a statement or statements once
– Then repeats the execution as long as a given
conditional expression evaluates to a truthy value
• Syntax
do {
statements;
} while (expression);
JavaScript, Sixth Edition 22
do/while Statements (cont’d.)
• Examples:
var count = 2;
do {
document.write("<p>The count is equal to " +↵
count + ".</p>");
count++;
} while (count < 2);
var count = 2;
while (count < 2) {
document.write("<p>The count is equal to " +↵
count + ".</p>");
count++;
}
JavaScript, Sixth Edition 23
do/while Statements (cont’d.)
• Example:
– adding days of week with a do/while statement
instead of a while statement
var i = 0;
do {
document.getElementsByTagName("th")[i].innerHTML =↵
daysOfWeek[i];
i++;
} while (i < 7);
JavaScript, Sixth Edition 24
for Statements
• for statement
– Repeats a statement or series of statements
• As long as a given conditional expression evaluates to
a truthy value
– Can also include code that initializes a counter and
changes its value with each iteration
• Syntax
for (counter_declaration; condition;
counter_operation) {
statements
}
JavaScript, Sixth Edition 25
for Statements (cont’d.)
• Steps when JavaScript interpreter encounters a for
loop
1. Counter variable declared and initialized
2. for loop condition evaluated
3. If condition evaluation in Step 2 returns truthy value:
• for loop statements execute, Step 4 occurs, and the
process starts over again with Step 2
If condition evaluation in Step 2 returns falsy value:
• for statement ends
• Next statement following the for statement executes
4. Update statement in the for statement executed
JavaScript, Sixth Edition 26
var brightestStars =
["Sirius", "Canopus", "Arcturus", "Rigel", "Vega"];
for (var count = 0; count < brightestStars.length; count++) {
document.write(brightestStars[count] + "<br />");
}
Result in browser:
for Statements (cont’d.)
JavaScript, Sixth Edition 27
var count = 1;
while (count < brightestStars.length) {
document.write(count + "<br />");
count++;
}
for (var count = 1; count < brightestStars.length; count++) {
document.write(count + "<br />");
}
for Statements (cont’d.)
• for statement
– More efficient than a while statement
• Examples:
JavaScript, Sixth Edition 28
for Statements (cont’d.)
• Example:
– addColumnHeaders() function with a for
statement instead of a do/while statement
function addColumnHeaders() {
for (var i = 0; i < 7; i++) {
document.getElementsByTagName("th")[i].innerHTML↵
= daysOfWeek[i];
}
}
JavaScript, Sixth Edition 29
Using continue Statements to Restart
Execution
• continue statement
– Halts a looping statement
• Restarts the loop with a new iteration
– Used to stop a loop for the current iteration
• Have the loop to continue with a new iteration
• Examples:
– for loop with a continue statement
JavaScript, Sixth Edition 30
for (var count = 1; count <= 5; count++) {
if (count === 3) {
continue;
}
document.write("<p>" + count + "</p>");
}
Result in browser:
Using continue Statements to Restart
Execution (cont’d.)
JavaScript, Sixth Edition 31
Making Decisions
• Decision making
– Process of determining the order in which statements
execute in a program
• Decision-making statements, decision-making
structures, or conditional statements
– Special types of JavaScript statements used for
making decisions
• if statement
– Most common type of decision-making statement
JavaScript, Sixth Edition 32
if Statements
• Used to execute specific programming code
– If conditional expression evaluation returns truthy
value
• Syntax
if (condition) {
statements
}
•
}After the if statement executes:
– Any subsequent code executes normally
JavaScript, Sixth Edition 33
if Statements (cont’d.)
• Use a command block to construct a decision-
making structure containing multiple statements
• Command block
– Set of statements contained within a set of braces
JavaScript, Sixth Edition 34
if/else Statements
• Executes one action if the condition is true
– And a different action if the condition is false
• Syntax for an if . . . else statement
if (expression) {
statements
}
else {
statements
}
JavaScript, Sixth Edition 35
if/else Statements (cont’d.)
• Example:
var today = "Tuesday"
if (today === "Monday") {
document.write("<p>Today is Monday</p>");
}
else {
document.write("<p>Today is not Monday</p>");
}
JavaScript, Sixth Edition 36
Nested if and if/else Statements
• Nested decision-making structures
– One decision-making statement contains another
decision-making statement
• Nested if statement
– An if statement contained within an if statement or
within an if/else statement
• Nested if/else statement
– An if/else statement contained within an if
statement or within an if/else statement
JavaScript, Sixth Edition 37
Nested if and if/else Statements
(cont’d.)
• Example:
var salesTotal = 75;
if (salesTotal > 50) {
if (salesTotal < 100) {
document.write("<p>The sales total is↵
between 50 and 100.</p>");
}
}
JavaScript, Sixth Edition 38
else if constructions
• Compact version of nested if/else statements
– combine an else statement with its nested if
statement
– requires fewer characters
– easier to read
JavaScript, Sixth Edition 39
else if constructions (cont'd.)
if (gameLocation[i] === "away") {
paragraphs[1].innerHTML = "@ ";
}
else if (gameLocation[i] === "home") {
paragraphs[1].innerHTML = "vs ";
}
if (gameLocation[i] === "away") {
paragraphs[1].innerHTML = "@ ";
}
else {
if (gameLocation[i] === "home") {
paragraphs[1].innerHTML = "vs ";
}
}
else if version
nested if/else version
JavaScript, Sixth Edition 40
else if constructions (cont'd)
• Used to create backward-compatible event listeners:
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", submitForm,↵
false);
}
else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", submitForm);
}
JavaScript, Sixth Edition 41
switch Statements
• Controls program flow by executing a specific set of
statements
• Dependent on an expression value
• Compares expression value to value contained
within a case label
• case label
– Represents a specific value
– Contains one or more statements that execute:
• If case label value matches the switch statement’s
expression value
JavaScript, Sixth Edition 42
switch Statements (cont’d.)
• Syntax switch (expression) {
case label:
statements;
break;193
case label:
statements;
break;
...
default:
statements;
break;
}
JavaScript, Sixth Edition 43
switch Statements (cont’d.)
• default label
– Executes when the value returned by the switch
statement expression does not match a case label
• When a switch statement executes:
– Value returned by the expression is compared to each
case label
• In the order in which it is encountered
• break statement
– Ends execution of a switch statement
– Should be final statement after each case label
JavaScript, Sixth Edition 44
function city_location(americanCity) {
switch (americanCity) {
case "Boston":
return "Massachusetts";
break;
case "Chicago":
return "Illinois";
break;
case "Los Angeles":
return "California";
break;
case "Miami":
return "Florida";
break;
case "New York":
return "New York";
break;
default:
return "United States";
break;
}
}
document.write("<p>" + city_location("Boston") + "</p>");
switch Statements (cont’d.)
JavaScript, Sixth Edition 45
Summary
• Array
– Set of data represented by a single variable name
– Index: element’s numeric position within the array
– Can access and modify array elements
– length property
• number of elements in an array
JavaScript, Sixth Edition 46
Summary (cont’d.)
• Loop statements
– while statements, do/while statements, and for
statements
– Iteration: each repetition of a looping statement
– Counter: variable
• Incremented or decremented with each iteration of a
loop statement
– continue statement
• Restarts a loop with a new iteration
JavaScript, Sixth Edition 47
Summary (cont’d.)
• Decision making
– Determining the order in which statements execute in
a program
• May execute in a linear fashion
– if statement,if/else statement, else if
construction
• Nested decision-making structures
– switch statement and case labels
– break statement: used to exit control statements
– Command block
• Set of statements contained within a set of braces
• May repeat the same statement, function, or code
section

Weitere ähnliche Inhalte

Was ist angesagt?

What's new with Apache Spark's Structured Streaming?
What's new with Apache Spark's Structured Streaming?What's new with Apache Spark's Structured Streaming?
What's new with Apache Spark's Structured Streaming?Miklos Christine
 
Static analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesStatic analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesAndrey Karpov
 
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...Yao Yao
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingIndicThreads
 
Distributed Real-Time Stream Processing: Why and How 2.0
Distributed Real-Time Stream Processing:  Why and How 2.0Distributed Real-Time Stream Processing:  Why and How 2.0
Distributed Real-Time Stream Processing: Why and How 2.0Petr Zapletal
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and IterationsSameer Wadkar
 
The Ring programming language version 1.5.4 book - Part 7 of 185
The Ring programming language version 1.5.4 book - Part 7 of 185The Ring programming language version 1.5.4 book - Part 7 of 185
The Ring programming language version 1.5.4 book - Part 7 of 185Mahmoud Samir Fayed
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for androidEsa Firman
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹Kros Huang
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaKros Huang
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysBlue Elephant Consulting
 
RxJava from the trenches
RxJava from the trenchesRxJava from the trenches
RxJava from the trenchesPeter Hendriks
 

Was ist angesagt? (20)

Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
What's new with Apache Spark's Structured Streaming?
What's new with Apache Spark's Structured Streaming?What's new with Apache Spark's Structured Streaming?
What's new with Apache Spark's Structured Streaming?
 
Static analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesStatic analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutes
 
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
 
Distributed Real-Time Stream Processing: Why and How 2.0
Distributed Real-Time Stream Processing:  Why and How 2.0Distributed Real-Time Stream Processing:  Why and How 2.0
Distributed Real-Time Stream Processing: Why and How 2.0
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and Iterations
 
The Ring programming language version 1.5.4 book - Part 7 of 185
The Ring programming language version 1.5.4 book - Part 7 of 185The Ring programming language version 1.5.4 book - Part 7 of 185
The Ring programming language version 1.5.4 book - Part 7 of 185
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Java 104
Java 104Java 104
Java 104
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
RxJava from the trenches
RxJava from the trenchesRxJava from the trenches
RxJava from the trenches
 

Ähnlich wie 9781305078444 ppt ch03

9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02Terry Yoast
 
java in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyajava in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyaviratandodariya
 
JAVA in Artificial intelligent
JAVA in Artificial intelligentJAVA in Artificial intelligent
JAVA in Artificial intelligentVirat Andodariya
 
JavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIJavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIAashish Jain
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in FlexChris Farrell
 
JavaScript Robotics
JavaScript RoboticsJavaScript Robotics
JavaScript RoboticsAnna Gerber
 
03-inheritance.ppt
03-inheritance.ppt03-inheritance.ppt
03-inheritance.pptSaiM947604
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 
UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2DianaGray10
 
Code transformation With Spoon
Code transformation With SpoonCode transformation With Spoon
Code transformation With SpoonGérard Paligot
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedureftz 420
 
Salesforce Summer 14 Release
Salesforce Summer 14 ReleaseSalesforce Summer 14 Release
Salesforce Summer 14 ReleaseJyothylakshmy P.U
 
Java Script
Java ScriptJava Script
Java ScriptSarvan15
 
Java Script
Java ScriptJava Script
Java ScriptSarvan15
 
Postman API testing with pre & post scripting
Postman API testing with pre & post scriptingPostman API testing with pre & post scripting
Postman API testing with pre & post scriptingITlearn360
 

Ähnlich wie 9781305078444 ppt ch03 (20)

9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02
 
java in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyajava in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariya
 
JAVA in Artificial intelligent
JAVA in Artificial intelligentJAVA in Artificial intelligent
JAVA in Artificial intelligent
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
JavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIJavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGI
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in Flex
 
JavaScript Robotics
JavaScript RoboticsJavaScript Robotics
JavaScript Robotics
 
03-inheritance.ppt
03-inheritance.ppt03-inheritance.ppt
03-inheritance.ppt
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2
 
Shooting the Rapids
Shooting the RapidsShooting the Rapids
Shooting the Rapids
 
Code transformation With Spoon
Code transformation With SpoonCode transformation With Spoon
Code transformation With Spoon
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
 
Salesforce Summer 14 Release
Salesforce Summer 14 ReleaseSalesforce Summer 14 Release
Salesforce Summer 14 Release
 
Scala test
Scala testScala test
Scala test
 
Scala test
Scala testScala test
Scala test
 
Java Script
Java ScriptJava Script
Java Script
 
Java Script
Java ScriptJava Script
Java Script
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Postman API testing with pre & post scripting
Postman API testing with pre & post scriptingPostman API testing with pre & post scripting
Postman API testing with pre & post scripting
 

Mehr von Terry Yoast

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12Terry Yoast
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11Terry Yoast
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10Terry Yoast
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09Terry Yoast
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08Terry Yoast
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07Terry Yoast
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06Terry Yoast
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05Terry Yoast
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04Terry Yoast
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01Terry Yoast
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13Terry Yoast
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18Terry Yoast
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17Terry Yoast
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16Terry Yoast
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15Terry Yoast
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14Terry Yoast
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12Terry Yoast
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11Terry Yoast
 
9781337102087 ppt ch10
9781337102087 ppt ch109781337102087 ppt ch10
9781337102087 ppt ch10Terry Yoast
 
9781337102087 ppt ch09
9781337102087 ppt ch099781337102087 ppt ch09
9781337102087 ppt ch09Terry Yoast
 

Mehr von Terry Yoast (20)

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 
9781337102087 ppt ch10
9781337102087 ppt ch109781337102087 ppt ch10
9781337102087 ppt ch10
 
9781337102087 ppt ch09
9781337102087 ppt ch099781337102087 ppt ch09
9781337102087 ppt ch09
 

Kürzlich hochgeladen

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Kürzlich hochgeladen (20)

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

9781305078444 ppt ch03

  • 1. JavaScript, Sixth Edition Chapter 3 Building Arrays and Controlling Flow
  • 2. JavaScript, Sixth Edition 2 Objectives In this chapter, you will: • Store data in arrays • Use while statements, do/while statements, and for statements to repeatedly execute code • Use continue statements to restart looping statements • Use if statements, if/else statements, and switch statements to make decisions • Nest one if statement in another
  • 3. JavaScript, Sixth Edition 3 Storing Data in Arrays • Array – Set of data represented by a single variable name Figure 3-1 Conceptual illustration of an array
  • 4. JavaScript, Sixth Edition 4 Declaring and Initializing Arrays • Array literal – most common way to create an array – declares a variable and specifies array as content • Syntax var name = [value1, value2, value3, …]; • Example: – Create an array named newsSections containing 4 strings as elements var newsSections = ["world","local","opinion","sports"]
  • 5. JavaScript, Sixth Edition 5 Declaring and Initializing Arrays (cont’d.) • Element – Each piece of data contained in an array • Index – Element’s numeric position within the array – Array element numbering • Starts with index number of zero (0) • Reference element using its index number – Example: to reference the 2nd element in the newsSections array newsSections[1]
  • 6. JavaScript, Sixth Edition 6 Declaring and Initializing Arrays (cont’d.) • Assigning values to individual array elements – Include the array index for an individual element • Example: – Add value "entertainment" as fifth element of newsSections array newsSections[4] = "entertainment";
  • 7. JavaScript, Sixth Edition 7 Declaring and Initializing Arrays (cont’d.) • Can create an array without any elements – Add new elements as necessary – Array size can change dynamically var colors = []; colors[2] = "yellow"; • JavaScript values assigned to array elements – Can be different data types
  • 8. JavaScript, Sixth Edition 8 Accessing Element Information • To access an element’s value: – Include brackets and element index • Examples: var sec1Head = document.getElementById("section1"); var sec2Head = document.getElementById("section2"); var sec3Head = document.getElementById("section3"); sec1Head.innerHTML = newsSections[0]; // "world" sec2Head.innerHTML = newsSections[1]; // "local"
  • 9. JavaScript, Sixth Edition 9 Modifying Elements • To modify values in existing array elements – Include brackets and element index • Can change a value assigned to an array element • Example: newsSections[4] = "living";
  • 10. JavaScript, Sixth Edition 10 Determining the Number of Elements in an Array • length property – Returns the number of elements in an array • Syntax name.length;
  • 11. JavaScript, Sixth Edition 11 Using the Array Object • JavaScript represents arrays with the Array object – Contains a special constructor named Array() • Constructor – Special function type used as the basis for creating reference variables • Syntax var newsSections = new Array(6); • Array literals preferred – Easier
  • 12. JavaScript, Sixth Edition 12 Referencing Default Collections of Elements • getElementsByTagName() method – Can reference web page element by looking up all elements of a certain type in document and referencing one element in that collection – Resulting collection uses syntax similar to arrays • Example: document.getElementsByTagName("li")[2]
  • 13. JavaScript, Sixth Edition 13 Repeating Code • Loop statement – Control flow statement repeatedly executing a statement or a series of statements • While a specific condition is true or until a specific condition becomes true • Three types of loop statements – while statements – do/while statements – for statements
  • 14. JavaScript, Sixth Edition 14 while Statements • while statement – Repeats a statement or series of statements • As long as a given conditional expression evaluates to a truthy value • Syntax while (expression) { statements } • Iteration – Each repetition of a looping statement
  • 15. JavaScript, Sixth Edition 15 while Statements (cont’d.) • Counter – Variable incremented or decremented with each loop statement iteration • Examples: – while statement using an increment operator – while statement using a decrement operator – while statement using the *= assignment operator
  • 16. JavaScript, Sixth Edition 16 var count = 1; while (count <= 5) { document.write(count + "<br />"); count++; } document.write("<p>You have printed 5 numbers.</p>"); while Statements (cont’d.) Result in browser:
  • 17. JavaScript, Sixth Edition 17 var count = 10; while (count > 0) { document.write(count + "<br />"); count--; } document.write("<p>We have liftoff.</p>"); while Statements (cont’d.) Result in browser:
  • 18. JavaScript, Sixth Edition 18 var count = 1; while (count <= 100) { document.write(count + "<br />"); count *= 2; } while Statements (cont’d.) Result in browser:
  • 19. JavaScript, Sixth Edition 19 while Statements (cont’d.) • Infinite loop – Loop statement that never ends • Conditional expression: never false – Example: var count = 1; while (count <= 10) { window.alert("The number is " + count + "."); }
  • 20. JavaScript, Sixth Edition 20 while Statements (cont’d.) • Example: – assigning array element values to table cells: function addColumnHeaders() { var i = 0; while (i < 7) { document.getElementsByTagName("th")↵ [i].innerHTML = daysOfWeek[i]; i++; } }
  • 21. JavaScript, Sixth Edition 21 do/while Statements • do/while statement – Executes a statement or statements once – Then repeats the execution as long as a given conditional expression evaluates to a truthy value • Syntax do { statements; } while (expression);
  • 22. JavaScript, Sixth Edition 22 do/while Statements (cont’d.) • Examples: var count = 2; do { document.write("<p>The count is equal to " +↵ count + ".</p>"); count++; } while (count < 2); var count = 2; while (count < 2) { document.write("<p>The count is equal to " +↵ count + ".</p>"); count++; }
  • 23. JavaScript, Sixth Edition 23 do/while Statements (cont’d.) • Example: – adding days of week with a do/while statement instead of a while statement var i = 0; do { document.getElementsByTagName("th")[i].innerHTML =↵ daysOfWeek[i]; i++; } while (i < 7);
  • 24. JavaScript, Sixth Edition 24 for Statements • for statement – Repeats a statement or series of statements • As long as a given conditional expression evaluates to a truthy value – Can also include code that initializes a counter and changes its value with each iteration • Syntax for (counter_declaration; condition; counter_operation) { statements }
  • 25. JavaScript, Sixth Edition 25 for Statements (cont’d.) • Steps when JavaScript interpreter encounters a for loop 1. Counter variable declared and initialized 2. for loop condition evaluated 3. If condition evaluation in Step 2 returns truthy value: • for loop statements execute, Step 4 occurs, and the process starts over again with Step 2 If condition evaluation in Step 2 returns falsy value: • for statement ends • Next statement following the for statement executes 4. Update statement in the for statement executed
  • 26. JavaScript, Sixth Edition 26 var brightestStars = ["Sirius", "Canopus", "Arcturus", "Rigel", "Vega"]; for (var count = 0; count < brightestStars.length; count++) { document.write(brightestStars[count] + "<br />"); } Result in browser: for Statements (cont’d.)
  • 27. JavaScript, Sixth Edition 27 var count = 1; while (count < brightestStars.length) { document.write(count + "<br />"); count++; } for (var count = 1; count < brightestStars.length; count++) { document.write(count + "<br />"); } for Statements (cont’d.) • for statement – More efficient than a while statement • Examples:
  • 28. JavaScript, Sixth Edition 28 for Statements (cont’d.) • Example: – addColumnHeaders() function with a for statement instead of a do/while statement function addColumnHeaders() { for (var i = 0; i < 7; i++) { document.getElementsByTagName("th")[i].innerHTML↵ = daysOfWeek[i]; } }
  • 29. JavaScript, Sixth Edition 29 Using continue Statements to Restart Execution • continue statement – Halts a looping statement • Restarts the loop with a new iteration – Used to stop a loop for the current iteration • Have the loop to continue with a new iteration • Examples: – for loop with a continue statement
  • 30. JavaScript, Sixth Edition 30 for (var count = 1; count <= 5; count++) { if (count === 3) { continue; } document.write("<p>" + count + "</p>"); } Result in browser: Using continue Statements to Restart Execution (cont’d.)
  • 31. JavaScript, Sixth Edition 31 Making Decisions • Decision making – Process of determining the order in which statements execute in a program • Decision-making statements, decision-making structures, or conditional statements – Special types of JavaScript statements used for making decisions • if statement – Most common type of decision-making statement
  • 32. JavaScript, Sixth Edition 32 if Statements • Used to execute specific programming code – If conditional expression evaluation returns truthy value • Syntax if (condition) { statements } • }After the if statement executes: – Any subsequent code executes normally
  • 33. JavaScript, Sixth Edition 33 if Statements (cont’d.) • Use a command block to construct a decision- making structure containing multiple statements • Command block – Set of statements contained within a set of braces
  • 34. JavaScript, Sixth Edition 34 if/else Statements • Executes one action if the condition is true – And a different action if the condition is false • Syntax for an if . . . else statement if (expression) { statements } else { statements }
  • 35. JavaScript, Sixth Edition 35 if/else Statements (cont’d.) • Example: var today = "Tuesday" if (today === "Monday") { document.write("<p>Today is Monday</p>"); } else { document.write("<p>Today is not Monday</p>"); }
  • 36. JavaScript, Sixth Edition 36 Nested if and if/else Statements • Nested decision-making structures – One decision-making statement contains another decision-making statement • Nested if statement – An if statement contained within an if statement or within an if/else statement • Nested if/else statement – An if/else statement contained within an if statement or within an if/else statement
  • 37. JavaScript, Sixth Edition 37 Nested if and if/else Statements (cont’d.) • Example: var salesTotal = 75; if (salesTotal > 50) { if (salesTotal < 100) { document.write("<p>The sales total is↵ between 50 and 100.</p>"); } }
  • 38. JavaScript, Sixth Edition 38 else if constructions • Compact version of nested if/else statements – combine an else statement with its nested if statement – requires fewer characters – easier to read
  • 39. JavaScript, Sixth Edition 39 else if constructions (cont'd.) if (gameLocation[i] === "away") { paragraphs[1].innerHTML = "@ "; } else if (gameLocation[i] === "home") { paragraphs[1].innerHTML = "vs "; } if (gameLocation[i] === "away") { paragraphs[1].innerHTML = "@ "; } else { if (gameLocation[i] === "home") { paragraphs[1].innerHTML = "vs "; } } else if version nested if/else version
  • 40. JavaScript, Sixth Edition 40 else if constructions (cont'd) • Used to create backward-compatible event listeners: var submitButton = document.getElementById("button"); if (submitButton.addEventListener) { submitButton.addEventListener("click", submitForm,↵ false); } else if (submitButton.attachEvent) { submitButton.attachEvent("onclick", submitForm); }
  • 41. JavaScript, Sixth Edition 41 switch Statements • Controls program flow by executing a specific set of statements • Dependent on an expression value • Compares expression value to value contained within a case label • case label – Represents a specific value – Contains one or more statements that execute: • If case label value matches the switch statement’s expression value
  • 42. JavaScript, Sixth Edition 42 switch Statements (cont’d.) • Syntax switch (expression) { case label: statements; break;193 case label: statements; break; ... default: statements; break; }
  • 43. JavaScript, Sixth Edition 43 switch Statements (cont’d.) • default label – Executes when the value returned by the switch statement expression does not match a case label • When a switch statement executes: – Value returned by the expression is compared to each case label • In the order in which it is encountered • break statement – Ends execution of a switch statement – Should be final statement after each case label
  • 44. JavaScript, Sixth Edition 44 function city_location(americanCity) { switch (americanCity) { case "Boston": return "Massachusetts"; break; case "Chicago": return "Illinois"; break; case "Los Angeles": return "California"; break; case "Miami": return "Florida"; break; case "New York": return "New York"; break; default: return "United States"; break; } } document.write("<p>" + city_location("Boston") + "</p>"); switch Statements (cont’d.)
  • 45. JavaScript, Sixth Edition 45 Summary • Array – Set of data represented by a single variable name – Index: element’s numeric position within the array – Can access and modify array elements – length property • number of elements in an array
  • 46. JavaScript, Sixth Edition 46 Summary (cont’d.) • Loop statements – while statements, do/while statements, and for statements – Iteration: each repetition of a looping statement – Counter: variable • Incremented or decremented with each iteration of a loop statement – continue statement • Restarts a loop with a new iteration
  • 47. JavaScript, Sixth Edition 47 Summary (cont’d.) • Decision making – Determining the order in which statements execute in a program • May execute in a linear fashion – if statement,if/else statement, else if construction • Nested decision-making structures – switch statement and case labels – break statement: used to exit control statements – Command block • Set of statements contained within a set of braces • May repeat the same statement, function, or code section