Java Reference
In-Depth Information
What is Functional Programming?
In JavaScript, functions are first-class objects, which means that they behave the same way
as every other value. So they can have their own properties and methods, as well as accept-
ing other functions as parameters and being returned by other functions. This makes them a
very flexible tool to work with in JavaScript, and there are a variety of techniques and pat-
terns that can be used to make code cleaner.
Functional programming involves using functions to perform a series of operations. Each
function forms an abstraction that should perform a single task, while encapsulating the de-
tails of its implementation inside the body of the function.
Here's an example of a random() function that will return a random integer between
two arguments, a and b ; if only one argument is supplied, it will return a random number
between 1 and that argument's value:
function random(a,b) {
if (b === undefined) b = a, a = 1; // if only one
argument is
supplied, assume the lower limit is 1
return Math.floor((b-a+1) * Math.random()) + a;
}
random(6);
<< 4
random(10,20);
<< 13
This is an example of an abstraction , as it wraps all the logic cleanly away inside the func-
tion.
Functions should not alter the underlying data they deal with―they should simply return a
different value, rather than change the value itself. This is known as non-destructive data
transformation . For example, the following function will return a string written backwards:
 
 
Search WWH ::




Custom Search