This document discusses functions in JavaScript. It defines a function as a block of code that performs a task and can be called multiple times. Functions are first-class objects that can be passed as arguments to other functions, returned from functions, and assigned to variables or object properties. Functions provide their own execution context and scope their variables to the function body. Functions are defined either with a function expression or function declaration and are called directly by name or indirectly via methods like call, apply, setTimeout. The value of the this keyword inside a function depends on how the function is called and refers to the execution context object.
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)