Functions
Functions contain blocks of code that need to be executed repeatedly. Functions can take zero or more arguments, and can optionally return a value.
Functions can be created in a variety of ways, two of which are shown below:
1
2
3
4
5
6
|
|
1
2
3
4
5
6
|
|
Using Functions
1
2
3
4
5
6
7
8
9
10
|
|
1
2
3
4
5
6
7
8
9
10
|
|
1
2
3
4
5
6
7
8
9
10
11
12
|
|
Immediately-Invoked Function Expression (IIFE)
A common pattern in JavaScript is the immediately-invoked function expression. This pattern creates a function expression and then immediately executes the function. This pattern is extremely useful for cases where you want to avoid polluting the global namespace with code — no variables declared inside of the function are visible outside of it.
1
2
3
4
5
6
7
8
|
|
Functions as Arguments
In JavaScript, functions are "first-class citizens" — they can be assigned to variables or passed to other functions as arguments. Passing functions as arguments is an extremely common idiom in jQuery.
1
2
3
4
5
6
7
8
9
10
|
|
1
2
3
4
5
6
7
8
9
10
11
12
|
|