2. Content
● What is a function?
● Defining functions
● Calling functions
● Context
3. What is a function?..
Mathematical:
f(x) -> x * x
Javascript:
function (x) {
return x * x;
}
Square Function
4. ...what else is a function?
● Functions are objects
○ function() {} instanceof Object //true
○ Can be passed as an argument
- doMagic(function () {})
- function magic() {}; addPower(magic);
○ Can have other objects/functions as properties
- typeof $ //"function"
- $.Event, $.ajax, $.each, etc..
○ Always passed by reference
- function addPower (fn) { fn.fire = true; }
- magic.fire //true;
5. ...what else is a function?
● Function is a scope provider
○ No scope in if (condition) { ... } else { ... } blocks
○ Variables are scoped to function's body block
6. ...what else is a function?
● Function is a scope provider
○ No scope in if (condition) { ... } else { ... } blocks
○ Variables are scoped to function's body block
7. Content
● What is a function?
● Defining functions
● Calling functions
● Context
8. Defining functions
● Function expression
○ var expression = function (arg1, arg2) { ... }
○ Anonymous callback functions
● Function declaration
○ function declaredFunction (arg1, arg2) { ... }
○ always hoisted to the top
○ named functions
● IIFE (Immediately-Invoked Function Expression)
○ (function () { ... })(); //Anonymous function
○ Used to create variable scopes (basically memory leaks)
○ Used to define modules (must return reference)