Agenda
- Why do we care?
- Functions Basics
- Functions are objects
- Functions Provide Scope
- Value and Reference
- Exercises
Why do we care?
-
We want to bring together data and functionaly into units that make sense to us.
-
We want to want minimize complexity by creating layers of abstraction and hiding the details.
-
We want to organize and share our work.
-
Using objects and functions we can also extend the language. We can create our own types and methods.
How does reverse work?
Do we care?
Components of a Function
A function is composed of four parts:
- The keyword
function
- The function name
- The function parameters
- The function body
Function Expression
There are two types of functions:
Function Statement
A function statement is short-hand for a function expression
Expression vs Statement - Simple Rule
If the first token is function
, you have a function statement
Functions Are Objects I
Functions are collections of name/value pairs. Just like objects, functions can be:
- Assigned to a variable
- Assigned to an object
- Passed as arguments to a function
- Returned from a function
- Can have methods and properties
- Can be created dynamically
Functions Are Objects II
Assigning a function to a variable.
Video: Functions Are Objects
Functions Provide Scope
Any variable declaration with a var
inside the function is invisible outside the function.
Scope within a Function
NOTE: child functions have access to parent functions variables and parameters
Your Turn ...
In the following exercise, your task is to output two different messages by adding one keyword.
Video: Functions Provide Scope
Video: Value and reference
Passing Primitive to Function
Function calls also pass primitive types by value.
Objects are Passed by Reference
Objects are never copied.
Object Inspection
Objects are never copied.
Within the Object
Primitive and object behavior holds.
Keeping the Object Reference
You can keep an object reference even while you reassign the variable - example below
Video: Value and reference