Because functional programming uses a completely different way of organizing programs, programmers who are accustomed to an imperative paradigm may find functional programming a bit difficult to learn. In this article, you'll learn some examples of how to write good, beautiful code in JavaScript using a functional style. I will discuss:
Functional programming concepts, including anonymous functions, different ways to call functions, and ways to pass functions as arguments to other functions.
Examples of the application of functional concepts include: extended array sorting; beautiful code generated by dynamic HTML; application of series functions.
Functional programming concepts
Please tell everyone. Please submit this to:
Digg
Slashdot
In languages that specify a solution to a problem by describing "how" , many developers know how to code. For example, to write a function that calculates the factorial, I could write a loop to describe the program, or use recursion to find the product of all numbers. In both cases, the calculation process is detailed in the program. Listing 1 shows a possible C code for calculating factorial.
List 1. Procedural style factorial
int factorial (int n)
{
if (n return 1;
else
return n * factorial (n-1);
}
This type of language is also called procedural programming language, because they define the process of solving problems. Functional programming differs significantly from this principle. In functional programming, you need to describe "what" the problem is.Functional programming languages are also called declarative languages. The same program for calculating factorial can be written as the product of all numbers up to n . A typical functional program for computing factorials looks like the example in Listing 2.
Listing 2. Functional style factorial
factorial n, where n factorial n := foldr * 1 take n [1.. ]
The second statement specifies to get a list of the first n numbers starting from 1 (take n [1..]), and then find their product, 1 is the base Yuan. This definition differs from the previous example in that there is no loop or recursion. It's like the arithmetic definition of the factorial function. Once you understand the meaning of library functions (take and foldr) and notations (list notation [ ]), writing code is easy and very readable.
With only three lines of Miranda code, you can write a routine that uses breadth-first or depth-first traversal to process each node of an n-ary tree, depending on the parameters, and the elements can be of any general type.
Historically, functional programming languages have been less popular for various reasons. But recently, some functional programming languages are making their way into the computer industry. One example is Haskell on the .NET platform. In other cases, existing languages borrow concepts from functional programming languages. Iterators and continuations in some C implementations, as well as some functional constructs provided in JavaScript, are examples of this borrowing. However, by borrowing functional constructs, the overall language programming paradigm does not change. JavaScript did not become a functional programming language just because of the addition of functional constructs.
I’m now going to discuss the various beauties of functional constructs in JavaScript and ways to use them in your daily coding and work. We'll start with some basic features and then look at some of the more interesting applications with them.
Anonymous functions
In JavaScript, you can write anonymous functions or functions without a name. Why is such a function needed? Read on, but first we'll learn how to write such a function. If you have the following JavaScript function:
List 3. Typical function
function sum(x,y,z) {
return (x y z);
}
Then the corresponding anonymous function should look like this:
Listing 4. Anonymous function
function(x,y,z) {
return (x y z) ;
}
To use it, you need to write the following code:
Listing 5. Applying anonymous functions
var sum = function(x,y,z) {
return (x y z);
}(1,2,3);
alert(sum);
Using functions as values
You can also use functions as values. You can also have variables whose assigned values are functions. In the last example, you can also do the following:
Listing 6. Using function assignment
var sum = function(x,y,z) {
return (x y z);
}
alert(sum(1,2,3));
In the example in Listing 6 above, the value assigned to the variable sum is the function definition itself. In this way, sum becomes a function and can be called anywhere.
Different ways to call functions
JavaScript allows two ways to call functions, as shown in Listings 7 and 8.
Listing 7. Typical function application
alert ("Hello, World!");
or
Listing 8. Using functions as expressions
(alert) ("Hello, World!");
So you can also write the following code:
Listing 9. After defining the function, you can use it immediately
( function(x,y,z) { return (x y z) } ) (1, 2, 3);
You can write function expressions in parentheses, and then pass them to parameters to perform operations on the parameters. Although in the example in Listing 8, there is the function name directly enclosed in parentheses, this is not the case when using it as shown in Listing 9.
Passing functions as arguments to other functions
You can also pass functions as arguments to other functions. Although this is not a new concept, it is used extensively in the following examples. Function parameters can be passed, as shown in Listing 10.
Listing 10. Passing a function as a parameter and applying the function
var passFunAndApply = function (fn,x,y,z) { return fn(x,y,z ); };
var sum = function(x,y,z) {
return x y z;
};
alert( passFunAndApply(sum,3,4,5 ) ); // 12
Executing the last alert statement outputs a value of size 12.
Using functional concepts
The previous section introduced some programming concepts using functional style. The examples given are not all-inclusive, nor are they in order of importance; they are just some that are relevant to this discussion. Here’s a quick summary of functional style in JavaScript:
Functions don’t always need names.
Functions can be assigned to variables like other values.
Function expressions can be written and placed in parentheses for later application.
Functions can be passed as parameters to other functions.
This section will introduce some examples of effective use of these concepts to write beautiful JavaScript code. (Using JavaScript's functional style, you can do many things beyond the scope of this discussion.)
Extended array sorting
First, let's write a sorting method that can sort data according to the date of the array elements. Writing this method in JavaScript is very simple. The sorting method of the data object accepts an optional parameter, which is the comparison function. Here, you need to use the comparison function from Listing 11.
Listing 11. Comparison function
function (x,y) {
return x.date – y.date;
}
To get the function you need, use the example in Listing 12.
Listing 12. Extension of sort function
arr.sort( function (x,y) { return x.date – y.date; });
Where arr is a type array object. The sort function sorts all objects in the arr array based on their date. The comparison function is passed to the sort function along with its definition to complete the sort operation. Use this function:
Every JavaScript object has a date property.
JavaScript’s array type sorting function accepts optional parameters, and the optional parameters are comparison functions used for sorting. This is similar to the qsort function in the C library.
Beautiful code for dynamically generating HTML
In this example, you will see how to write beautiful code to dynamically generate HTML from an array. Tables can be generated based on the values obtained from the data. Alternatively, you can use the contents of an array to generate sorted and unsorted lists. Vertical or horizontal menu items can also be generated.
The code style in Listing 13 is commonly used to generate dynamic HTML from arrays.
Listing 13. Ordinary code to generate dynamic HTML
var str=' ';
for (var i=0;i
str =... HTML generation code...
}
document.write(str);
You can replace this code with the code in Listing 14.
Listing 14. Common way to generate dynamic HTML
Array.prototype.fold=function(templateFn) {
var len=this.length;
var str =' ';
for (var i=0; i
return str;
}
function templateInstance(element) {
return ... HTML generation code ...
}
document.write(arr.fold(templateInstance));
I use the prototype attribute of the Array type to define the new function fold. This function can now be used on any array defined later.
Application of a series of functions
Consider the following situation: you want to use a set of functions as callback functions. To achieve this, the window.setTimeout function will be used, which takes two parameters. The first parameter is the function to be called after the number of milliseconds indicated by the second parameter. Listing 15 shows one way to accomplish this.
Listing 15. Calling a set of functions in callbacks
window.setTimeout(function(){alert('First!');alert('Second!');}, 5000);
Listing 16 shows a better way to do this.
Listing 16. A better way to call a series of functions
Function.prototype.sequence=function(g) {
var f=this;
return function () {
f();g();
}
};
function alertFrst() { alert('First!'); }
function alertSec() { alert( 'Second!'); }
setTimeout( alertFrst.sequence(alertSec), 5000);
When processing an event, if you want to call another callback after calling it Callbacks can also be extended using the code in Listing 16. This might be an exercise for you to complete on your own, now that your interest is piqued.
Back to top
Conclusion
In many fields You can use functional programming in JavaScript to complete daily activities in a beautiful way. The examples in this article illustrate just a few scenarios. If you find the right context for functional programming and apply the concepts, you'll gain more understanding and increase your elegance.
More from