Control Flow
-
the control flow is the order in wheich the computer executes statements in a script
-
Code is run in order from the first line in the file to the last line, unless the computer runs across the (extremely frequent) structures that change the control flow, such as conditionals and loops.
-
Control flow means that when you read a script, you must not only read from start to finish but also look at program structure and how it affects order of execution.
JS Functions
-
A JavaScript function is a block of code designed to perform a particular task
-
A JavaScript function is executed when "something" invokes it (calls it)
JS Function Syntax
-
A JavaScript function is defined with the
functionkeyword, followed by a name, followed by parentheses() -
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables)
-
The code to be executed, by the function, is placed inside curly brackets:
{}
Function Invocation
- The code inside the function will execute when "something" invokes (calls) the function:
-
when the event occurs (when the user clicks a button)
-
when it is invoked (called) from JS code
-
automatically (self invoked)
-
Function Retun
- *When JavaScript reaches a
returnstatement, the function will stop executing.
If the function was invoked from a statement, JS will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller"
Why Functions
-
you can reuse code: define code once, and use it many times
-
you can use the same code many times with different arguments, to produce different results
The () Operator invokes the Function
- Using the example above,
toCelsiusrefers to the function object, andtoCelsius()refers to the function result. Accessing a function without()will return the function object instead of the function result
Functions used as Variables
- Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations
Local Variables
-
Variables declared within a JavaScript function, become
LOCALto the function -
Local variables can only be accessed from within the function