Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Higher-order programming in Javascript

In this article we will describe higher order programming in javascript. Higher order programming is a special type of implementation which can be used in both functional and object oriented programming.

Introduction

Higher order programming is a special concept where the function itself is passed as arguments. In normal programming practice, we transfer parameters (variables) as values from one function to another function. So to understand the concept, we must have some idea about the function call which passes arguments to another function. The other functions use the argument as input and process it. Some time the processed value is also returned to the calling function as per the requirement. In higher order programming, functions are passed to other functions as arguments. The other functions use the received function as input and process it. And if required, the function is also returned as return value. The concept of higher order programming is mainly used in functional model but it can also be used in object oriented programming. As we know, javascript plays a major role on web development area, so higher order programming can be used easily in web development.

Using function as argument

In general, we use javascript as a tool for developing front end tasks like validation, window pop up, alert etc. But if we consider advanced level, then there are so many functionalities available to implement. And these functionalities are helpful for the development of complex tasks. Now we will take a sample example to describe higher order programming concepts, where we pass function as argument to another function. For simplicity, we will take javascript 'sort' method to implement the concept. Generally we use sort method to sort array elements. The simple code document.write {[8, 6, 9, 10].sort ()} will give output as "6, 8, 9, 10". This is a very simple task which we use regularly in normal programming practice. Now let’s take a look what advanced feature is available for the developers which will add value to our programming. The sort method implements higher order programming by allowing compare function as an optional argument. Let’s assume we have an array of objects and each object is having date property associated with it. Now we want to sort the array objects based on their date value. The following example does the same for us.

Listing 1: Sample code displaying function passing as arguments

arrayObjs.sort(

  functionNew (m,n) {

    return m.date-n.date;

  }

);

In this example we have used the sort function and functionNew() is passed as argument. So if we check the arguments of sort function, then the other function is available for working. Now let’s discuss how it works internally. In sort function, the compare function is called regularly. So if we use the optional function (which is compare) then it returns positive, negative and zero value based on the value of m and n. It returns negative value when n>m, positive value when m>n and zero when both are equal.

Using function as return value

In this section we will describe another aspect of higher order programming, which is returning function as return value. In general programming, the return value from a function is normally another value which is received by the calling function. But here we will show an example where the return value is another function. In html page we use different tag elements for different purposes. We generally make templates to make the design of the html page. Let’s try to form some function which will return the formatted element with tags attached.

Listing 2: Sample code displaying function as return value

function wrapElement(newtag) {

  var starttag='<'+newtag+'>';

  var endtag='</'+newtag+'>';

  return function(a) {

    return starttag+a+endtag;

  }

}  

document.write(wrapElement('u')('make it under lined.'));

var u=wrapElement('u’);

document.write(u('make it underlined too.'));

In this example we have made a template which will underline a text passed to the function wrapElement (). Inside the function we have made the necessary formatting and returned the end result to the calling function. Here the return value is another function which is performing the tasks. So this technique can be used for all types of formatting and also for performing more advances tasks/functions.

Using function as object

The concept of object comes in object oriented programming languages like java, C++ etc. In these languages everything is considered as objects and then is represented by class. But in javascript, the concept is a bit different. Here the functions are also treated as objects. These functions can also have methods so a function is javascript can also be extended.

Using methods as functions

Now we will discuss how methods can be used as function and the implementation details. Before we discuss the implementation, we need to understand the concept of 'this' parameter. The 'this' parameter is very important when it is used inside a method of an object. It always refers to the object to which the methods belong. But the problem is, when a method is used as event handler or callback function. In this type of scenario, 'this' parameter does not point to the object to which methods belong to. To solve the problem, javascript uses a local variable and the value of 'this' is assigned to that variable. So here the local variable always refers to the correct object.

Listing 3: Sample code displaying use of methods as function

function sendAlert(textme) {
  this.textme=textme;
  var localme=this;
  this.invoke=function () {
    alert(localme.textme);
  }
}
 
var sayHello=new sendAlert('Hello, How are you!');
div.attachEvent('onclick', sayHello.invoke);

Let’s take another example where we are trying to make template for html generation. The second document.write () will fail as the parameter ‘this’ has a different meaning to the called reduce () function.

Listing 4: Sample code displaying tag elements

function wrapElement(tag) {

  this.starttag='<'+tag+'>';

  this.endtag='</'+tag'>';

  this.wrap=function(a) {

    return this.starttag+a+this.endtag;

  }

}

Para=new wrapElement('P');


// The following code will work
document.write (Para.wrap ('This is a paragraph tag for writing'));

 
// The following code will not work as ‘this’ has a different meaning
document.write (arr.reduce (Para.wrap));

To solve the issue lets add a local variable which will take the value from ‘this’ parameter and refers to the correct object.

Listing 5: Sample code displaying the use of local variable to get the value from ‘this’ parameter

function wrapElement(tag) {

  this.starttag='<'+tag+'>';

  this.endtag='</'+tag'>';
  
  var useme=this;

  this.wrap=function(a) {

    return useme.starttag+a+useme.endtag;

  }

}

Para=new wrapElement('P');

// The following code will work
document.write (Para.wrap (' This is a paragraph tag for writing'));

 
// The following code will also work
document.write (arr.reduce (Para.wrap));

Closures in JavaScript

In functional programming there is a concept called 'closures'. Some time functional programming and closures are described as similar concepts. But those are not exactly the same concept. So closures can be described as the combination of the following two.

  • It is a function returned by another function
  • It is a closed environment where the returned function is forced to execute

When to use higher order programming

The higher order programming is a useful concept I javascript. But we need to identify the proper place to implement it. Higher order programming concepts are mainly used in the following areas.

Modularization

In modern programming field modular programming is become the main important factor during design of the application. The modular program is easy to maintain and test. Each module performs separate tasks and hence more complete in nature and functionality. So here also the concept of higher order programming is implemented. For example, we can have a scenario where several functions are there but they are almost similar except a minor part of code. So here we can consolidate the generic part in a single function and make separate functions for the different parts. This new function (which is different and not generic) is passed to the more general function as an argument. So the higher order programming concept like passing function as argument is implemented.

Object oriented programming

In javascript object oriented flavor can be implemented using higher order programming. So in applications where javascript plays a major role, higher order programming is very useful.

Conclusion

To conclude the discussion we can say that javascript can also be used in more structured way by following the concepts of higher order programming. Higher order programming gives the flexibility of functional programming, modularization and also object oriented concepts.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login