Skip to content

Latest commit

 

History

History
65 lines (31 loc) · 2.32 KB

File metadata and controls

65 lines (31 loc) · 2.32 KB

Programming with JavaScript

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 function keyword, 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:
    1. when the event occurs (when the user clicks a button)

    2. when it is invoked (called) from JS code

    3. automatically (self invoked)

Function Retun

  • *When JavaScript reaches a return statement, 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, toCelsius refers to the function object, and toCelsius() 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 LOCAL to the function

  • Local variables can only be accessed from within the function