Javascript Subroutines Jasleen Kaur Fall 2011

31 downloads 47 Views 91KB Size Report
10 Oct 2011 ... Selection. ❑ Iteration. ❑ Sub-routine (suspend and resume). ➢ Also known as ( AKA): functions, procedures, methods. Seen… Next. Javascript.
10/10/2011

COMP 110: Introduction to Programming WWW

Javascript Subroutines Jasleen Kaur Fall 2011

© Copyright: Jasleen Kaur. 2011.

1

Introduction to Programming

Top-down approach 

So far, seen some JS syntax 



Top-down approach:   



But how do you solve a problem using it?

Divide problem into smaller problems Stress WHAT over HOW Keep dividing, until WHAT Æ HOW is easy

Example: payroll

payroll read info

Becomes documentation (comments)

read rate

display

hours overtime salary

salary

… prompt

© Copyright: Jasleen Kaur. 2011.

read hours

calculate



prompt

Introduction to Programming

2

1

10/10/2011

Recall building blocks 

Sequence of instructions  

Assignment I/O    

  

alert prompt confirm document.write

Seen…

Selection Iteration Sub-routine (suspend and resume) 

Next

Also known as (AKA): functions, procedures, methods Javascript

© Copyright: Jasleen Kaur. 2011.

Introduction to Programming

3

Recall suspend-and-resume Do this

Function Call Suspend Resume Done



Subroutines rely on the suspend-and-resume paradigm

© Copyright: Jasleen Kaur. 2011.

Introduction to Programming

4

2

10/10/2011

Functions reserved keyword



function name() { … code … }

function name

What?  

Code Separate from “main” program  “main” – part that executes automatically





Functions: executed only when explicitly called

Example: function myAlert() { alert(“Hello there”); }

© Copyright: Jasleen Kaur. 2011.

Introduction to Programming

5

Location 

Function definition:  



Put within in header (within ) Code is not executed when encountered by browser

Function call: 

In within (referred to as “main” code) myAlert(); // suspends to execute function code, // returns & resumes after function is // executed

© Copyright: Jasleen Kaur. 2011.

Introduction to Programming

6

3

10/10/2011

What causes sub-routines to end? 1. Reaches end of code “}”  It runs out of function code to execute

2. Explicit return statement return;  Often, in an if statement:

if (done) return;

3. Error



Where does it return? 

To position from where it was called

© Copyright: Jasleen Kaur. 2011.

Introduction to Programming

7

4