JavaScript 4 Functions
JavaScript 4 Functions
JavaScript:
Functions
Slides 2016 Marty Hall, hall@coreservlets.com
For additional materials, please see http://www.coreservlets.com/. The JavaScript tutorial section contains
complete source code for all examples in the entire tutorial series, plus exercises and exercise solutions for each topic.
Intro
JavaScript has more in common with functional languages like Lisp or Scheme than with C or Java.
- JSON and YUI guru Douglas Crockford in article
JavaScript: The Worlds Most Misunderstood Programming Language
For additional materials, please see http://www.coreservlets.com/. The JavaScript tutorial section contains
complete source code for all examples in the entire tutorial series, plus exercises and exercise solutions for each topic.
Getting Good at JavaScript
Experience with other languages can be an impediment here
If you try to program JavaScript like Java 7 and earlier, you will never be good at
JavaScript. Java 8 and later have functional programming capabilities, however.
Beginners or programmers from Ruby, Lisp, Scheme, Python, ML, Haskell, Clojure, Scala
sometimes do better
Functional programming, not object-oriented programming, is key
Functional programming is much more central to JavaScript programming than OOP is
Java programmers (at least prior to Java 8) find functional programming to be the single-
hardest part of JavaScript to learn
OOP in JavaScript is radically different than in most languages
So different in fact, that some argue that by some definitions of OOP, JavaScript does not
have real OOP
6
Overview
You can have global functions
Not just methods (functions as part of objects)
You dont declare return types or argument types
function square(x) { return(x * x); }
You never say the input (x) or the output (x * x) are numbers
Functions are first-class datatypes
You can pass functions around, store them in arrays, etc.
You can create anonymous functions
function foo(...) {...}
var foo = function(...) {...}
You can also have anonymous functions that capture local variables (closures)
This capability is critical to Ajax (discussed in the jQuery section)
Functions can have methods
Just as strings and arrays can
7
coreservlets.com custom onsite training
Assigning Functions to
Variables, Arrays, and Other
Data Structures
Slides 2016 Marty Hall, hall@coreservlets.com
For additional materials, please see http://www.coreservlets.com/. The JavaScript tutorial section contains
complete source code for all examples in the entire tutorial series, plus exercises and exercise solutions for each topic.
It is Lisp in Cs clothing.
- Douglas Crockford describing the JavaScript language in JavaScript: The Good Parts
9
Assigning to Variables
function square(x) {
return(x*x);
}
square(5); 25
f(10); 100
10
Passing
Functions to
Other Functions
Slides 2016 Marty Hall, hall@coreservlets.com
For additional materials, please see http://www.coreservlets.com/. The JavaScript tutorial section contains
complete source code for all examples in the entire tutorial series, plus exercises and exercise solutions for each topic.
13
Simple Examples
function applyToSeven(funct) {
return(funct(7));
}
applyToSeven(square); 49
applyToSeven(double); 14
function applyTwice(funct, value) {
return(funct(funct(value)));
}
applyTwice(square, 5); 625
function applyRepeatedly(funct, value, numRepeats) {
for(var i=0; i<numRepeats; i++) {
value = funct(value);
}
return(value);
}
applyRepeatedly(double, 5, 3); 40
14
Returning
Functions from
Functions
Slides 2016 Marty Hall, hall@coreservlets.com
For additional materials, please see http://www.coreservlets.com/. The JavaScript tutorial section contains
complete source code for all examples in the entire tutorial series, plus exercises and exercise solutions for each topic.
Functions are First-Class Data Types
Can assign functions to variables
Can put functions in arrays (or other data structures)
Can pass functions to other functions
Can return functions from functions
Can create functions without assigning them to variables
(anonymous functions)
Can create functions that capture local variables (closures)
Functions can have methods, just as strings and arrays can
18
Example
function square(x) { return(x*x); }
function double(x) { return(x*2); }
function randomFunct() {
if(Math.random() > 0.5) {
return(square);
} else {
return(double)
}
}
var ran = randomFunct();
ran(5) 25 // Or, could be 10
ran(5) 25 // Will always match value above
ran(5) 25 // Will always match value above
ran = randomFunct();
ran(5) 10 // Or, could be 25
19
coreservlets.com custom onsite training
Creating
Anonymous
Functions
Slides 2016 Marty Hall, hall@coreservlets.com
For additional materials, please see http://www.coreservlets.com/. The JavaScript tutorial section contains
complete source code for all examples in the entire tutorial series, plus exercises and exercise solutions for each topic.
21
Basics
Simple anonymous functions
var square = function(x) { return(x * x); };
square(5); 25
(function(x) { return(x * x); })(10) 100
Equivalent constructs
function square(x) {
return(x * x);
}
var square = function(x) {
return(x * x);
};
The bottom one is actually widely used in real life so that you can define functions
within namespaces as shown in the upcoming section on objects.
var namespace = {};
var namespace.functionName = function(...) { ... };
22
function randomFunct() {
if(Math.random() > 0.5) {
return(square);
} else {
return(double)
}
}
Drawback: not self contained
Relies on square and double already being defined
Changes in functionality if double and square are redefined
23
Redoing randomFunction
With local named functions
function randomFunct2() {
function square(x) { return(x*x); }
function double(x) { return(x*2); }
if(Math.random() > 0.5) {
return(square);
} else {
return(double)
}
}
var f = randomFunct2();
f(10); 100 // Or maybe 20
(randomFunct2())(10); 20 // Or maybe 100
24
Redoing randomFunction
With anonymous functions
function randomFunct3() {
if(Math.random() > 0.5) {
return(function (x) { return(x*x); });
} else {
return(function (x) { return(x*2); })
}
}
var f = randomFunct3();
f(10); 100 // Or maybe 20
(randomFunct3())(10); 20 // Or maybe 100
25
coreservlets.com custom onsite training
Capturing Local
Variables (Making
Closures)
Slides 2016 Marty Hall, hall@coreservlets.com
For additional materials, please see http://www.coreservlets.com/. The JavaScript tutorial section contains
complete source code for all examples in the entire tutorial series, plus exercises and exercise solutions for each topic.
27
Function-Creating Function
With fixed value
function makeTimes7Function() {
return(function(n) { return(n*7); });
}
var f = makeTimes7Function();
f(5); 35
With dynamic value
function makeMultiplierFunction(m) {
return(function(n) { return(n*m); });
}
var test = 8;
var f = makeMultiplierFunction(test);
f(5); 40
test = 500;
28 f(5); 40 // Not 2500. The closure has private copy of m (8)
For additional materials, please see http://www.coreservlets.com/. The JavaScript tutorial section contains
complete source code for all examples in the entire tutorial series, plus exercises and exercise solutions for each topic.
Functions are First-Class Data Types
Can assign functions to variables
Can put functions in arrays (or other data structures)
Can pass functions to other functions
Can return functions from functions
Can create functions without assigning them to variables
(anonymous functions)
Can create functions that capture local variables (closures)
Functions can have methods, just as strings and arrays can
30
32
Wrap-up
For additional materials, please see http://www.coreservlets.com/. The JavaScript tutorial section contains
complete source code for all examples in the entire tutorial series, plus exercises and exercise solutions for each topic.
Summary
Can assign functions to variables
var f = square;
Can put functions in arrays (or other data structures)
var functs = [square, f, double];
Can pass functions to other functions
callIt(square, 7);
Can return functions from functions
return(square);
Can create functions without assigning them to variables
(function(x) { return(x*x); })(8); 64
Can create functions that capture local variables (closures)
var f = makeMultiplierFunction(5);
Can use apply if arguments are already in array
34 Math.max.apply(null, [1, 3, 5, 7, 6, 4, 2]); 7
For additional materials, please see http://www.coreservlets.com/. The JavaScript tutorial section contains
complete source code for all examples in the entire tutorial series, plus exercises and exercise solutions for each topic.