25 Functions
25 Functions
Lecture 25
2
Defining a function
function name(paramName, ..., paramName) {
statements;
}
• example:
function sumTo(n) {
var sum = 0;
for (var i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
3
Returning values
function maybeReturn(n) {
if (n % 2 == 0) {
return "even";
}
// else return undefined
}
9
Two ways to declare a function
• The following are equivalent:
10
Array higher-order functions *
.every(function) accepts a function that returns a boolean value
and calls it on each element until it returns false
.filter(function) accepts a function that returns a boolean; calls it
on each element, returning a new array of the
elements for which the function returned true
.forEach(function) applies a "void" function to each element
.map(function) applies function to each element; returns new array
.reduce(function) accepts a function that accepts pairs of values and
.reduce(function, combines them into a single value; calls it on each
element starting from the front, using the given
initialValue) initialValue (or element [0] if not passed)
.reduceRight(functio
n) reduceRight starts from the end of the array
.reduceRight(functio
n,
12
Nested functions
// adds 1 to each element of an array of
numbers
function incrementAll(a) {
function increment(n) { return n + 1; }
var result = a.map(increment);
return result;
}
13
Invocation patterns
• functions can be invoked in four ways in JavaScript:
as a normal function
as a method of an object
as a constructor
through their apply property
14
Functions as methods
• an object's methods are just properties that are functions
the function uses the this keyword to refer to the object
> var teacher = {
name: "Tyler Durden",
salary: 0.25,
greet: function(you) {
print("Hi " + you + ", I'm " +
this.name);
},
toString: function() {
return "Prof. " + this.name;
}
};
> teacher.greet("kids");
Hi kids, I'm Tyler Durden
15
Function binding
{ ...
propertyName: function, // bind at
... // declaration
}
var b1 = document.getElementById("b1");
JS
b1.onclick = function() { ... };
20
How to curry functions
function toArray(a, i) { // converts a
var result = [], i = i || 0; // duck-typed obj
while (i < a.length) { // into an array
result.push(a[i++]);
}
return result;
};
function curry(f) { // Usage: curry(f,
arg1, ...)
var args = toArray(arguments, 1); // remove f
return function() {
return f.apply(this,
args.concat(toArray(arguments)));
};
}
22
A JS library: Underscore
http://documentcloud.github.com/underscore/
• Adds functional language methods to JavaScript.
Collections: each, map, reduce, reduceRight, detect, select, reject, all, any,
include, invoke, pluck, max, min, sortBy, sortedIndex, toArray, size
Arrays: first, rest, last, compact, flatten, without, uniq, intersect, zip,
indexOf, lastIndexOf, range
Functions: bind, bindAll, memoize, delay, defer, wrap, compose
Objects: keys, values, functions, extend, clone, tap, isEqual, isEmpty,
isElement, isArray, isArguments, isFunction, isString, isNumber, isBoolean,
isDate, isRegExp, isNaN, isNull, isUndefined
Utility: noConflict, identity, times, breakLoop, mixin, uniqueId, template
Chaining: chain, value