JavaScript, Sixth Edition

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Tonight’s JavaScript Topics 1 Conditional Statements: if and switch The Array Object Looping Statements: for, while and do-while.
Creating PHP Pages Chapter 7 PHP Decisions Making.
Objectives Using functions to organize PHP code
PHP Conditions MIS 3501, Fall 2014 Jeremy Shafer Department of MIS Fox School of Business Temple University September 11, 2014.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Tutorial 12 Working with Arrays, Loops, and Conditional Statements
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 5: Control Structures II (Repetition)
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Tutorial 4 Decision Making with Control Structures and Statements Section A - Decision Making JavaScript Tutorial 4 -Decision Making with Control.
CSCI 116 Week 3 Functions & Control Structures. 2 Topics Using functions Using functions Variable scope and autoglobals Variable scope and autoglobals.
Introduction to JavaScript for Python Programmers
TODAY’S LECTURE Review Chapter 2 Go over exercises.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Arrays and Control Structures CST 200 – JavaScript 2 –
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Decision Making with Control Structures and Statements (non-audio version) © Dr. David.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
Control Structures By Shyam Gurram. Control Structure In this chapter we have two different types of structures. Conditional Structure Iterative Control.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to.
ALBERT WAVERING BOBBY SENG. Week 4: JavaScript  Quiz  Announcements/questions.
L OO P S While writing a program, there may be a situation when you need to perform some action over and over again. In such situation you would need.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
JavaScript, Fourth Edition
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow.
Programming Perl in UNIX Course Number : CIT 370 Week 3 Prof. Daniel Chen.
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
Working with Loops, Conditional Statements, and Arrays.
XP Tutorial 3 New Perspectives on JavaScript, Comprehensive1 Working with Arrays, Loops, and Conditional Statements Creating a Monthly Calendar.
JavaScript and Ajax (Control Structures) Week 4 Web site:
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Chapter 22 Selection and Iteration if ( Boolean Expression ) true statement ; else false statement ; OperatorMeaning ! Logical not < Less than
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Chapter 5: Looping. Using the while Loop Loop – A structure that allows repeated execution of a block of statements Loop body – A block of statements.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
JavaScript, Sixth Edition
Tutorial 12 Working with Arrays, Loops, and Conditional Statements
Chapter 3: Decisions and Loops
JavaScript Syntax and Semantics
CiS 260: App Dev I Chapter 4: Control Structures II.
Expressions and Control Flow in JavaScript
JavaScript: Control Statements.
JavaScript: Control Statements I
ITM 352 Flow-Control: Loops
Arrays, For loop While loop Do while loop
Chapter 8 JavaScript: Control Statements, Part 2
Control Structures Functions Decision making Loops
T. Jumana Abu Shmais – AOU - Riyadh
Objectives In this chapter, you will:
Chap 7. Advanced Control Statements in Java
CIS 136 Building Mobile Apps
Chapter 8 JavaScript: Control Statements, Part 2
Presentation transcript:

JavaScript, Sixth Edition Chapter 3 Building Arrays and Controlling Flow

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

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

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

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

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

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

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" sec3Head.innerHTML = newsSections[2]; // "opinion" JavaScript, Sixth Edition

Modifying Elements newsSections[4] = "living"; 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

Determining the Number of Elements in an Array length property Returns the number of elements in an array Syntax name.length; JavaScript, Sixth Edition

Using the Array Object var newsSections = new Array(6); 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

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

Repeating Code Loop statement Three types of loop statements 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

while Statements while statement Syntax Iteration 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

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

while Statements (cont’d.) var count = 1; while (count <= 5) { document.write(count + "<br />"); count++; } document.write("<p>You have printed 5 numbers.</p>"); Result in browser: JavaScript, Sixth Edition

while Statements (cont’d.) var count = 10; while (count > 0) { document.write(count + "<br />"); count--; } document.write("<p>We have liftoff.</p>"); Result in browser: JavaScript, Sixth Edition

while Statements (cont’d.) var count = 1; while (count <= 100) { document.write(count + "<br />"); count *= 2; } Result in browser: JavaScript, Sixth Edition

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

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

do/while Statements do/while statement Syntax 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

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

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

for Statements for statement Syntax 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

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

for Statements (cont’d.) var brightestStars = ["Sirius", "Canopus", "Arcturus", "Rigel", "Vega"]; for (var count = 0; count < brightestStars.length; count++) { document.write(brightestStars[count] + "<br />"); } Result in browser: JavaScript, Sixth Edition

for Statements (cont’d.) More efficient than a while statement Examples: var count = 1; while (count < brightestStars.length) { document.write(count + "<br />"); count++; } for (var count = 1; count < brightestStars.length; count++) { document.write(count + "<br />"); } JavaScript, Sixth Edition

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

Using continue Statements to Restart Execution 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

Using continue Statements to Restart Execution (cont’d.) for (var count = 1; count <= 5; count++) { if (count === 3) { continue; } document.write("<p>" + count + "</p>"); Result in browser: JavaScript, Sixth Edition

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

if Statements 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

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

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 { JavaScript, Sixth Edition

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

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

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

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

else if constructions (cont'd.) nested if/else version 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 JavaScript, Sixth Edition

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

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

switch Statements (cont’d.) Syntax switch (expression) { case label: statements; break;193 break; ... default: } JavaScript, Sixth Edition

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

switch Statements (cont’d.) function city_location(americanCity) { switch (americanCity) { case "Boston": return "Massachusetts"; break; case "Chicago": return "Illinois"; case "Los Angeles": return "California"; case "Miami": return "Florida"; case "New York": return "New York"; default: return "United States"; } document.write("<p>" + city_location("Boston") + "</p>"); JavaScript, Sixth Edition

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

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

Summary (cont’d.) Decision making May execute in a linear fashion 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 JavaScript, Sixth Edition