Presentation is loading. Please wait.

Presentation is loading. Please wait.

Control Structures Functions Decision making Loops

Similar presentations


Presentation on theme: "Control Structures Functions Decision making Loops"— Presentation transcript:

1 Control Structures Functions Decision making Loops

2 Functions Controlling when code executes

3 Functions vs. Methods A JavaScript function is a block of code designed to perform a particular task – an action of some sort A JavaScript function is executed when "something" invokes it (calls it). You can create your own functions, as we will learn later, or use JS built-in functions, also called intrinsic functions. Intrinsic Functions are built into Javascript objects, so they get a special name, they are called methods. Functions are NOT associated with an object, whereas Methods are! Functions must be contained within a <script> element

4 Defining Functions function nameOfFunction(parameters) { statements; }
Syntax function nameOfFunction(parameters) { statements; } Parameter Variable used within a function Placed within parentheses following a function name Multiple parameters allowed calc_square_root(number1, number2)

5 Lets Practice Define a function named “displayMyBank”
Inside the function, use a document.write statement, to write out the name of your bank The function does not need parameters Syntax function nameOfFunction(parameters) { statements; }

6 Calling Functions Function statements do the actual work and are contained within curly braces Functions can be written anywhere in the web page, but are usually within the document head, or an external .js file Calls to the function are within the body section and consist of the function name followed by parentheses function printStudentNames() { document.write(“<p>” + Joe + “</p>”); document.write(“<p>” + Sam + “</p>”); document.write(“<p>” + Bob + “</p>”); } </script> </head> <body> <script> printStudentNames(); </script>

7 Calling Functions using parameters
If a function needs additional information, providing it is called Passing arguments The function must be designed to receive that data, and that data is called a parameter Arguments vs. Parameters – refer to the same memory location, therefore the same data function averageNumbers(a, b, c) { var sum_of_numbers = a + b + c; var result = sum_of_numbers / 3; return result; } averageNumbers(1,2,3);

8 Lets Practice Write the function named “displayMyName” which receives a memory location. The function will refer to the memory location using the parameter name someonesName Next, Write a statement to call the function named “displayMyName” providing it your own name as an argument Refer to the example below: function averageNumbers(a, b, c) { var sum_of_numbers = a + b + c; var result = sum_of_numbers / 3; return result; } averageNumbers(1,2,3);

9 Functions which return data
A function can return information to the statement that called it A Return statement Returns a value to the statement calling the function Uses the return keyword with the variable or value to send to the calling statement

10 Calling Functions (cont’d.)
Example of a function receiving parameters and returning result: function averageNumbers(a, b, c) { var sum_of_numbers = a + b + c; var result = sum_of_numbers / 3; return result; } var ans; ans=averageNumbers(1,2,3);

11 Understanding Variable Scope
Where in a program a declared variable can be used Global variable Declared outside a function Available to all parts of a program Local variable Declared inside a function Only available within the function in which it is declared Cease to exist when the function ends Keyword var required

12 Understanding Variable Scope (cont’d.)
If variable declared within a function and does not include the var keyword Variable automatically becomes a global variable Program may contain global and local variables with the same name Local variable takes precedence Value assigned to local variable of the same name Not assigned to global variable of the same name

13 Understanding Variable Scope (cont’d.)
var pitcher = "Josh Beckett"; function duplicateVariableNames() { var pitcher = "Tim Lincecum"; document.write("<p>" + pitcher + "</p>"); // value printed is Tim Lincecum } duplicateVariableNames(); // value printed is Josh Beckett

14 Lets Practice Inside your function, “displayMyBank”
Declare a variable called myBank and set it’s value to the name of your bank Modify the document.write statement, to write out the name of your bank, using the variable

15 Functions vs. Methods At this point, just think of a function as something you create, and a method is a function that someone already created, and is available thru an object. The syntax for using a method is: ObjectName.methodname(); For example, the document object has a method called write, so when we want to use it, we type document.write(); Some methods need information and some do not. If information is needed, it goes INSIDE the parenthesis, as in document.write(“My name is Monica”);

16 Document Object - getElementByID
A powerful Method is getElementByID. This method allows JavaScript to interact with an HTML element. To do so, you pass getElementByID the name of the HTML element you are interested in, as in document.getElementByID(“tax”) So, somewhere in the HTML of the page, there has to be a field named “tax”, as in <input type=“text” id=“tax” value=“” /> Now that the html element, in this case a textbox, can be referenced, you can decide what part of it you want to work with. In this case, its value, as in document.getElementByID(“tax”).value

17 More methods Being able to reference what the user types into a form field, such as a textbox, is what gives Javascript its gusto! It does pose problems, because we do not know for sure what the user may have typed. If we expect the user to type a number in our textbox, there is no guarantee they will do that. So, we need to check what is entered, to make sure the right stuff is entered. We do this by using 1 or more of these additional methods: isNaN parseInt parseFloat

18 isNaN() The isNaN() method determines whether a value is an illegal number (Not-a-Number) This function returns true if the value is NaN, and false if it is Syntax isNaN(value) document.write(isNaN("Ima String"))  isNan returns true document.write(isNaN(0/0))  isNan returns true document.write(isNaN("348"))  isNan returns false document.write(isNaN(348))  isNan returns false

19 parseInt() The parseInt() method parses a string and returns an integer. If the first character cannot be converted to a number, parseInt() returns NaN (not a number) document.write(parseInt("10") + "<br />");  parseInt returns 10 document.write(parseInt("10.33") + "<br />");  parseInt returns 10 document.write(parseInt(" ") + "<br />");  parseInt returns 34 document.write(parseInt(" 60 ") + "<br />");  parseInt returns 60 document.write(parseInt("He was 40") + "<br />");  parseInt returns NaN

20 parseFloat() The parseFloat() method n parses a string and returns a floating point number document.write(parseFloat("10") + "<br />");  parseFloat returns 10 document.write(parseFloat("10.33") + "<br />");  parseFloat returns document.write(parseFloat(" ") + "<br />");  parseFloat returns 34 document.write(parseFloat(" 60 ") + "<br />");  parseFloat returns 60 document.write(parseFloat("He was 40") + "<br />");  parseFloat returns NaN

21 Putting it all together
Suppose we have a web page that has a textbox on it, and we want the user to only enter a number in the textbox. We can ensure this, using a combination of functions: getElementById to get the value of what they typed isNaN – to see if they typed a number alert – to tell them if they made an error, and if no errors, parseInt or parseFloat to convert the number in the textbox to a true integer or decimal

22 FLOW CONTROL FlowCHARTS

23 Flow Control Flowcharts
Process of determining the order in which statements execute in a program Special types of JavaScript statements used in flow control Flowcharts A diagram that uses special symbols to display the flow of execution in a program Handy to ensure program reaches a logical conclusion Comprised of various symbols

24 Designing Program Flow
Start and End symbols Indicate the beginning and end of the program Arrows Show flow of control Input/Output Accept data or represent the results of computations Decision Contain a yes/no question or a true/false test Connector Entry point/hookup point Process Show a statement; piece of logic Start

25 Designing Program Flow for sweaters.html
Start Declare variables for prices Assign values to variables Display line 1 Display line 2 Display line 3 Display line 4 End

26 Decisions Flow control using: if and switch commands

27 Making Decisions Decision making
Process of determining which statements execute in a program Decision-making statements, decision-making structures, or conditional statements Used when you need to adopt one path out of the given two paths Conditional statements allow your program to make correct decisions and perform right actions Runs a command or command block only when certain circumstances are met JavaScript supports 2 kinds of conditional statements which are used to perform different actions based on different conditions if .. else switch

28 if Statements – single action
Used to execute specific programming code If conditional expression evaluation returns a truthy value Syntax if (condition) { javascript statements ) } Command block begins/ends with curly braces

29 If/else Statements – dual action
Tests a condition and has 2 possible actions if (condition) { JS commands if condition is true } else JS commands ifconditions Is not true yes no

30 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>");

31 if and if/else Statements – multiple actions
Nested decision-making structures One decision-making statement contains another decision-making statement

32 if and if/else Statements – multiple actions
Nested if statement An if statement contained within an if statement or within an if/else statement var salesTotal = 75; if (salesTotal > 50) { if (salesTotal < 100) { document.write("<p>The sales total is between 50 and 100.</p>"); }

33 Nested if/elseif statements
An if/else statement contained within an if statement or within an if/else statement if (gameLocation[i] === "away") { paragraphs[1].innerHTML = "; } else { if (gameLocation[i] === "home") { paragraphs[1].innerHTML = "vs "; nested if/else version if (gameLocation[i] === "away") { paragraphs[1].innerHTML = "; } else if (gameLocation[i] === "home") { paragraphs[1].innerHTML = "vs "; else if version

34 switch Statements Controls program flow by executing a specific set of statements based on an expression until a match is found Examines the expression and then evaluates a series of possible values see if a value meets the criteria (sort of like a multiple choice question) The switch statement is given an expression to evaluate The case statements contain the possible values and the code to execute for each possible value The interpreter checks each case against the value of the expression until a match is found If nothing matches, a default condition will be used. Break statement stops the matching

35 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>");

36 REPETITION Flow of control using: while, do while, AND for-in commands

37 Working with Program Loops
A program loop is a set of commands that is executed repeatedly until a stopping condition has been met Four kinds of loops While Do While For For loop Requires a counter variable tracks the number of times a set of commands is run The collection of commands that is run each time through a loop is collectively known as a command block

38 while Statements while (expression) { 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 } NEW TERM!! Iteration Each repetition of a looping statement

39 while Statements (cont’d.)
A WHILE statement runs as long as a specific condition is met 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

40 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:

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

42 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 is ??:

43 while Statements (cont’d.)
Infinite loop Loop statement that never ends Example: var count = 1; while (count <= 10) { window.alert("The number is " + count + "."); } WHATS CAUSING THIS TO NEVER STOP?

44 do/while Statements do/while statement Syntax
Similar to the while loop except that the condition check happens at the end of the loop. Executes a statement or statements at least once Then repeats the execution as long as a given conditional expression evaluates to a truthy value Syntax do { statements; } while (expression); Note the semicolon used at the end of the do...while loop

45 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++; }

46 for Statements Repeats a statement or series of statements Syntax
Most compact form of looping Includes the following three important parts: The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out. The iteration statement where you can increase or decrease your counter Repeats a statement or series of statements As long as a given conditional expression evaluates to a truthy value Syntax for (counter_declaration; condition; counter_modifier) { statements }

47 for Statements (cont’d.)
For loops are often used to cycle through the different values contained within an array To loop through the contents of an array, use length property: var brightestStars = ["Sirius", "Canopus", "Arcturus", "Rigel", "Vega"]; for (var count = 0; count < brightestStars.length; count++) { document.write(brightestStars[count] + "<br />"); } Result in browser:

48 for Statements (cont’d.)
var count = 1; while (count < brightestStars.length) { document.write(count + "<br />"); count++; } for (var count = 1; count < brightestStars.length; count++) { document.write(count + "<br />"); }

49 “For In” Loop This loop is used to loop through an object's properties or associative arrays. SYNTAX for (myvariablename in object) { statement or block to execute; } In each iteration one property from object is assigned to variablename and this loop continues until all the properties of the object are exhausted. for (var x in Array) { txt=txt + Array[x]; } alert(txt);

50 Using continue Statements to Resume Execution
for (var count = 1; count <= 5; count++) { if (count === 3) { continue; } document.write("<p>" + count + "</p>"); Result in browser:

51 Using BREAK Statements to Exit Execution
for (var count = 1; count <= 5; ++count) { if (count == 3) break; document.write("<p>" + count + "</p>"); }


Download ppt "Control Structures Functions Decision making Loops"

Similar presentations


Ads by Google