Project 2a due Monday | |||
Kasparov and Deep Jr. are tied |
A function is a package for an algorithm; once written, it can be use over and over. |
Functions have a specific syntax | |||
function <name> ( <parameter list> ) { | |||
<function definition> | |||
} | |||
<name> names are identifiers; start w/letter | |||
<parameter list> is the input variables, a list separated by commas | |||
<function definition> is just the program to do the work | |||
Compute the Body Mass Index when the inputs are in metric | |||
function <name> ( <parameter list> ) { | |||
<function definition> | |||
} |
Most programming is done by writing functions, so learning the form is key |
A function is declared by writing down the “package” … the function is used when it is called |
Declaration: the function “package,” says what happens when the function runs | |||
Call: the function use, asks for the computation to be run | |||
There is only one function declaration | |||
There can be many calls … functions are reusable | |||
In JS, functions tend to be grouped together but the calls go where they are needed |
Suppose we compute “weight in Au” | |||
Worth = (Weight*12)*368.4 |
Suppose we compute “weight in Au” | |||
Worth = (Weight*12)*368.4 |
Suppose we compute “weight in Au” | |||
Worth = (Weight*12)*368.4 |
Suppose we compute “weight in Au” | |||
Worth = (Weight*12)*368.4 |
No one writes perfect programs the first time … smart programmers check | |
To test, have a standard page handy |
Put a function declaration in <script> |
Reviewing properties of functions | |||
Selecting names … don’t use alert() | |||
Parameter variables … don’t need to be declared, but work like local variables | |||
Scope of Reference … refers to where in the program a variable is “known,” i.e. where its value can be referenced and/or assigned |
Global … declared outside of functions |
Parameters vs Arguments … parameters are the “formal” variables in the function declaration; arguments are the same thing in the call |
Functions are packages for algorithms | |||
They follow a series of rules, that quickly become intuitive | |||
Functions have both a declaration and a call | |||
Functions have both parameters (in the declaration) and arguments (in the call) | |||
Scope refers to the region of a program where a variable is “known” |