Chapter 11. Coding and Design Patterns

Now that you know all about the objects in JavaScript, mastered prototypes and inheritance, and seen some practical examples of using browser-specific objects, let's move forward, or rather, move a level up. Let's take a look at some common JavaScript patterns.

But first, what's a pattern? In short, a pattern is a good solution to a common problem. Codifying the solution into a pattern makes it repeatable as well.

Sometimes, when you're facing a new programming problem, you may recognize right away that you've previously solved another, suspiciously similar problem. In such cases, it's worth isolating this class of problems and searching for a common solution. A pattern is a proven and reusable solution (or an approach to a solution) to a class of problems.

There are cases where a pattern is nothing more than an idea or a name. Sometimes, just using a name helps you think more clearly about a problem. Also, when working with other developers in a team, it's much easier to communicate when everybody uses the same terminology to discuss a problem or a solution.

Other times, you may come across a unique problem that doesn't look like anything you've seen before and doesn't readily fit into a known pattern. Blindly applying a pattern just for the sake of using a pattern, is not a good idea. It's preferable to not use any known pattern than to try to tweak your problem so that it fits an existing solution.

This chapter talks about two types of patterns, which are as follows:

  • Coding patterns: These are mostly JavaScript-specific best practices
  • Design patterns: These are language-independent patterns, popularized by the famous Gang of Four book

Coding patterns

Let's start with some patterns that reflect JavaScript's unique features. Some patterns aim to help you organize your code, for example, namespacing; others are related to improving performance, such as lazy definitions and init-time branching; and some make up for missing features, such as private properties. The patterns discussed in this section include the following topics:

  • Separating behavior
  • Namespaces
  • Init-time branching
  • Lazy definition
  • Configuration objects
  • Private variables and methods
  • Privileged methods
  • Private functions as public methods
  • Immediate functions
  • Chaining
  • JSON

Separating behavior

As discussed previously, the three building blocks of a web page are as follows:

  • Content (HTML)
  • Presentation (CSS)
  • Behavior (JavaScript)

Content

HTML is the content of the web page, the actual text. Ideally, the content should be marked-up using the least amount of HTML tags that sufficiently describe the semantic meaning of that content. For example, if you're working on a navigation menu, it's a good idea to use the <ul> and <li> tags as a navigation menu is in essence, just a list of links.

Your content (HTML) should be free from any formatting elements. Visual formatting belongs to the presentation layer and should be achieved through the use of CSS (Cascading Style Sheets). This means the following:

  • The style attribute of HTML tags should not be used, if possible.
  • Presentational HTML tags such as <font> should not be used at all.
  • Tags should be used for their semantic meaning, not because of how browsers render them by default. For instance, developers sometimes use a <div> tag where a <p> would be more appropriate. It's also favorable to use <strong> and <em> instead of <b> and <i> as the latter describe the visual presentation rather than the meaning.

Presentation

A good approach to keep presentation out of the content is to reset or nullify all browser defaults, for example, using reset.css from the Yahoo! UI library. This way, the browser's default rendering won't distract you from consciously thinking about the proper semantic tags to use.

Behavior

The third component of a web page is the behavior. Behavior should be kept separate from both the content and the presentation. It is usually added by using JavaScript that is isolated to <script> tags, and preferably contained in external files. This means not using any inline attributes, such as onclick, onmouseover, and so on. Instead, you can use the addEventListener/attachEvent methods from the previous chapter.

The best strategy to separate behavior from content is as follows:

  • Minimize the number of <script> tags
  • Avoid inline event handlers
  • Do not use CSS expressions
  • Toward the end of your content, when you are ready to close the <body> tag, insert a single external.js file

Example of separating behavior

Let's say you have a search form on a page, and you want to validate the form with JavaScript. So, you go ahead and keep the form tags free from any JavaScript, and then immediately before closing the </body> tag, you insert a <script> tag that links to an external file, as follows:

    <body> 
      <form id="myform" method="post" action="server.php"> 
      <fieldset> 
        <legend>Search</legend> 
        <input 
          name="search" 
          id="search" 
          type="text"   
        /> 
        <input type="submit" /> 
        </fieldset> 
      </form> 
      <script src="behaviors.js"></script> 
    </body> 

In behaviors.js you attach an event listener to the submit event. In your listener, you can check to see if the text input field was left blank and, if so, stop the form from being submitted. This way, you will save a roundtrip between the server and the client and make the application immediately responsive.

The content of behaviors.js is given in the following code. It assumes that you've created your myevent utility from the exercise at the end of the previous chapter:

    // init 
    myevent.addListener('myform', 'submit', function (e) { 
      // no need to propagate further 
      e = myevent.getEvent(e); 
      myevent.stopPropagation(e); 
      // validate 
      var el = document.getElementById('search'), 
      if (!el.value) { // too bad, field is empty 
        myevent.preventDefault(e); // prevent the form submission 
        alert('Please enter a search string'), 
      } 
    }); 

Asynchronous JavaScript loading

You noticed how the script was loaded at the end of the HTML, right before closing the body. The reason is that JavaScript blocks the DOM construction of the page, and in some browsers, even downloads of the other components that follow. By moving the scripts to the bottom of the page, you ensure that the script is out of the way, and when it arrives, it simply enhances the already usable page.

Another way to prevent external JavaScript files from blocking the page is to load them asynchronously. This way you can start loading them earlier. HTML5 has the defer attribute for this purpose. Consider the following line of code:

    <script defer src="behaviors.js"></script> 

Unfortunately, the defer attribute is not supported by older browsers, but luckily, there is a solution that works across browsers, old and new. The solution is to create a script node dynamically and append it to the DOM. In other words, you can use a bit of inline JavaScript to load the external JavaScript file. You can have this script loader snippet at the top of your document so that the download has an early start. Take a look at the following code example:

    ... 
    <head> 
    <script> 
    (function () { 
      var s = document.createElement('script'), 
      s.src = 'behaviors.js'; 
      document.getElementsByTagName('head')[0].appendChild(s); 
    }()); 
    </script> 
    </head> 
    ... 

Namespaces

Global variables should be avoided in order to reduce the possibility of variable naming collisions. You can minimize the number of globals by namespacing your variables and functions. The idea is simple, you will create only one global object, and all your other variables and functions become properties of that object.

An Object as a namespace

Let's create a global object called MYAPP:

    // global namespace 
    var MYAPP = MYAPP || {}; 

Now, instead of having a global myevent utility (from the previous chapter), you can have it as an event property of the MYAPP object, as follows:

    // sub-object 
    MYAPP.event = {}; 

Adding the methods to the event utility is still the same. Consider the following example:

    // object together with the method declarations 
    MYAPP.event = { 
      addListener: function (el, type, fn) { 
        // .. do the thing 
      }, 
      removeListener: function (el, type, fn) { 
        // ... 
      }, 
      getEvent: function (e) { 
        // ... 
      } 
      // ... other methods or properties 
    }; 

Namespaced constructors

Using a namespace doesn't prevent you from creating constructor functions. Here is how you can have a DOM utility that has an Element constructor, which allows you to create DOM elements easily:

    MYAPP.dom = {}; 
    MYAPP.dom.Element = function (type, properties) { 
      var tmp = document.createElement(type); 
      for (var i in properties) { 
        if (properties.hasOwnProperty(i)) { 
          tmp.setAttribute(i, properties[i]); 
        } 
      } 
       return tmp; 
    }; 

Similarly, you can have a Text constructor to create text nodes. Consider the following code example:

    MYAPP.dom.Text = function (txt) { 
      return document.createTextNode(txt); 
    }; 

Using the constructors to create a link at the bottom of a page can be done as follows:

    var link = new MYAPP.dom.Element('a',  
      {href: 'http://phpied.com', target: '_blank'}); 
    var text = new MYAPP.dom.Text('click me'), 
    link.appendChild(text); 
    document.body.appendChild(link); 

A namespace() method

You can create a namespace utility that makes your life easier so that you can use more convenient syntax as follows:

    MYAPP.namespace('dom.style'), 

Instead of the more verbose syntax as follows:

    MYAPP.dom = {}; 
    MYAPP.dom.style = {}; 

Here's how you can create such a namespace() method. First, you will create an array by splitting the input string using the period (.) as a separator. Then, for every element in the new array, you will add a property to your global object, if one doesn't already exist, as follows:

    var MYAPP = {}; 
    MYAPP.namespace = function (name) { 
      var parts = name.split('.'), 
      var current = MYAPP; 
      for (var i = 0; i < parts.length; i++) { 
        if (!current[parts[i]]) { 
          current[parts[i]] = {}; 
        } 
        current = current[parts[i]]; 
      } 
    }; 

Testing the new method is done as follows:

    MYAPP.namespace('event'), 
    MYAPP.namespace('dom.style'), 

The result of the preceding code is the same as if you did the following:

    var MYAPP = { 
      event: {}, 
      dom: { 
        style: {} 
      } 
    }; 

Init-time branching

In the previous chapter, you noticed that sometimes, different browsers have different implementations for the same or similar functionalities. In such cases, you will need to branch your code, depending on what's supported by the browser currently executing your script. Depending on your program, this branching can happen far too often and, as a result, may slow down the script execution.

You can mitigate this problem by branching some parts of the code during initialization, when the script loads, rather than during runtime. Building upon the ability to define functions dynamically, you can branch and define the same function with a different body, depending on the browser. Let's see how.

First, let's define a namespace and placeholder method for the event utility:

    var MYAPP = {}; 
    MYAPP.event = { 
      addListener: null, 
      removeListener: null 
    }; 

At this point, the methods to add or remove a listener are not implemented. Based on the results from feature sniffing, these methods can be defined differently, as follows:

    if (window.addEventListener) { 
      MYAPP.event.addListener = function (el, type, fn) { 
        el.addEventListener(type, fn, false); 
      }; 
      MYAPP.event.removeListener = function (el, type, fn) { 
        el.removeEventListener(type, fn, false); 
      }; 
    } else if (document.attachEvent) { // IE 
      MYAPP.event.addListener = function (el, type, fn) { 
        el.attachEvent('on' + type, fn); 
      }; 
      MYAPP.event.removeListener = function (el, type, fn) { 
        el.detachEvent('on' + type, fn); 
      }; 
    } else { // older browsers 
      MYAPP.event.addListener = function (el, type, fn) { 
        el['on' + type] = fn; 
      }; 
      MYAPP.event.removeListener = function (el, type) { 
        el['on' + type] = null; 
      }; 
    } 

After this script executes, you have the addListener() and removeListener() methods defined in a browser-dependent way. Now, every time you invoke one of these methods, there's no more feature-sniffing, and it results in less work and faster execution.

One thing to watch out for when sniffing features is not to assume too much after checking for one feature. In the previous example, this rule is broken because the code only checks for addEventListener support, but then defines both addListener() and removeListener(). In this case, it's probably safe to assume that if a browser implements addEventListener(), it also implements removeEventListener(). However, imagine what happens if a browser implements stopPropagation() but not preventDefault(), and you haven't checked for these individually. You have assumed that because addEventListener() is not defined, the browser must be an old IE and write your code using your knowledge and assumptions of how IE works. Remember that all of your knowledge is based on the way a certain browser works today, but not necessarily the way it will work tomorrow. So, to avoid many rewrites of your code as new browser versions are shipped, it's best to individually check for features you intend to use and don't generalize on what a certain browser supports.

Lazy definition

The lazy definition pattern is similar to the previous init-time branching pattern. The difference is that the branching happens only when the function is called for the first time. When the function is called, it redefines itself with the best implementation. Unlike the init-time branching, where the if happens once, during loading, here it may not happen at all, in cases when the function is never called. The lazy definition also makes the initialization process lighter as there's no init-time branching work to be done.

Let's see an example that illustrates this via the definition of an addListener() function. The function is first defined with a generic body. It checks which functionality is supported by the browser when it's called for the first time and then redefines itself using the most suitable implementation. At the end of the first call, the function calls itself, so that the actual event attaching is performed. The next time you call the same function, it will be defined with its new body and be ready for use, so no further branching is necessary. The following is the code snippet:

    var MYAPP = {}; 
    MYAPP.myevent = { 
     addListener: function (el, type, fn) { 
        if (el.addEventListener) { 
          MYAPP.myevent.addListener = function (el, type, fn) { 
            el.addEventListener(type, fn, false); 
          }; 
        } else if (el.attachEvent) { 
          MYAPP.myevent.addListener = function (el, type, fn) { 
            el.attachEvent('on' + type, fn); 
          }; 
        } else { 
          MYAPP.myevent.addListener = function (el, type, fn) { 
            el['on' + type] = fn; 
          }; 
        } 
        MYAPP.myevent.addListener(el, type, fn); 
      } 
    }; 

Configuration object

This pattern is convenient when you have a function or method that accepts a lot of optional parameters. It's up to you to decide how many constitutes a lot. But generally, a function with more than three parameters is not convenient to call, because you have to remember the order of the parameters, and it is even more inconvenient when some of the parameters are optional.

Instead of having many parameters, you can use one parameter and make it an object. The properties of the object are the actual parameters. This is suitable to pass configuration options because these tend to be numerous and optional (with smart defaults). The beauty of using a single object as opposed to multiple parameters is described as follows:

  • The order doesn't matter
  • You can easily skip parameters that you don't want to set
  • It's easy to add more optional configuration attributes
  • It makes the code more readable because the configuration object's properties are present in the calling code along with their names

Imagine you have some sort of UI widget constructor you use to create fancy buttons. It accepts the text to put inside the button (the value attribute of the <input> tag) and an optional parameter of the type of button. For simplicity, let's say the fancy button takes the same configuration as a regular button. Take a look at the following code:

    // a constructor that creates buttons 
    MYAPP.dom.FancyButton = function (text, type) { 
      var b = document.createElement('input'), 
      b.type = type || 'submit'; 
      b.value = text; 
      return b; 
    }; 

Using the constructor is simple; you just give it a string. Then, you can add the new button to the body of the document as follows:

    document.body.appendChild( 
      new MYAPP.dom.FancyButton('puuush') 
    ); 

This is all well and works fine, but then you decide you also want to be able to set some of the style properties of the button, such as colors and fonts. You can end up with a definition like the following:

    MYAPP.dom.FancyButton =  
      function (text, type, color, border, font) { 
      // ... 
    }; 

Now, using the constructor can become a little inconvenient, especially when you want to set the third and fifth parameter, but not the second or the fourth. Consider the following example:

    new MYAPP.dom.FancyButton( 
      'puuush', null, 'white', null, 'Arial'), 

A better approach is to use one config object parameter for all the settings. The function definition can become something like the following code snippet:

    MYAPP.dom.FancyButton = function (text, conf) { 
      var type = conf.type || 'submit'; 
      var font = conf.font || 'Verdana'; 
      // ... 
    }; 

Using the constructor is shown as follows:

    var config = { 
      font: 'Arial, Verdana, sans-serif', 
      color: 'white' 
    }; 
    new MYAPP.dom.FancyButton('puuush', config); 

Another usage example is as follows:

    document.body.appendChild( 
      new MYAPP.dom.FancyButton('dude', {color: 'red'}) 
    ); 

As you can see, it's easy to set only some of the parameters and to switch around their order. In addition, the code is friendlier and easier to understand when you see the names of the parameters at the same place where you call the method.

A drawback of this pattern is the same as its strength. It's trivial to keep adding more parameters, which means trivial to abuse the technique. Once you have an excuse to add to this free-for-all bag of properties, you will find it tempting to keep adding some that are not entirely optional, or some that are dependent on other properties.

As a rule of thumb, all these properties should be independent and optional. If you have to check all possible combinations inside your function ("oh, A is set, but A is only used if B is also set"), this is a recipe for a large function body, which quickly becomes confusing and difficult, if not impossible, to test, because of all the combinations.

Private properties and methods

JavaScript doesn't have the notion of access modifiers, which set the privileges of the properties in an object. Other languages often have access modifiers, as follows:

  • Public: All users of an object can access these properties or methods
  • Private: Only the object itself can access these properties
  • Protected: Only objects inheriting the object in question can access these properties

JavaScript doesn't have a special syntax to denote private properties or methods, but as discussed in Chapter 3, Functions, you can use local variables and methods inside a function and achieve the same level of protection.

Continuing with the example of the FancyButton constructor, you can have local variable styles that contains all the defaults, and a local setStyle() function. These are invisible to the code outside of the constructor. Here's how FancyButton can make use of the local private properties:

    var MYAPP = {}; 
    MYAPP.dom = {}; 
    MYAPP.dom.FancyButton = function (text, conf) { 
      var styles = { 
        font: 'Verdana', 
        border: '1px solid black', 
        color: 'black', 
        background: 'grey' 
      }; 
      function setStyles(b) { 
        var i; 
        for (i in styles) { 
          if (styles.hasOwnProperty(i)) { 
            b.style[i] = conf[i] || styles[i]; 
          } 
       } 
      } 
      conf = conf || {}; 
      var b = document.createElement('input'), 
      b.type = conf.type || 'submit'; 
      b.value = text; 
      setStyles(b); 
      return b; 
    }; 

In this implementation, styles is a private property and setStyle() is a private method. The constructor uses them internally (and they can access anything inside the constructor), but they are not available to code outside of the function.

Privileged methods

Privileged methods (this term was coined by Douglas Crockford) are normal public methods that can access private methods or properties. They can act like a bridge in making some of the private functionality accessible, but in a controlled manner, wrapped in a privileged method.

Private functions as public methods

Let's say you've defined a function that you absolutely need to keep intact, so you make it private. However, you also want to provide access to the same function, so that outside code can also benefit from it. In this case, you can assign the private function to a publicly available property.

Let's define _setStyle() and _getStyle() as private functions, but then assign them to the public setStyle() and getStyle(), consider the following example:

    var MYAPP = {}; 
    MYAPP.dom = (function () { 
      var _setStyle = function (el, prop, value) { 
        console.log('setStyle'), 
      }; 
      var _getStyle = function (el, prop) { 
        console.log('getStyle'), 
      }; 
      return { 
        setStyle: _setStyle, 
        getStyle: _getStyle, 
        yetAnother: _setStyle 
      }; 
    }()); 

Now, when you call MYAPP.dom.setStyle(), it invokes the private _setStyle() function. You can also overwrite setStyle() from the outside as follows:

    MYAPP.dom.setStyle = function () {alert('b'),}; 

Now, the result is as follows:

  • MYAPP.dom.setStyle points to the new function
  • MYAPP.dom.yetAnother still points to _setStyle()
  • _setStyle() is always available when any other internal code relies on it to be working as intended, regardless of the outside code

When you expose something private, keep in mind that objects (functions and arrays are objects too) are passed by reference and, therefore, can be modified from the outside.

Immediate functions

Another pattern that helps you keep the global namespace clean is to wrap your code in an anonymous function and execute that function immediately. This way, any variables inside the function are local, as long as you use the var statement, and are destroyed when the function returns, if they aren't part of a closure. This pattern was discussed in more detail in Chapter 3, Functions. Take a look at the following code:

    (function () { 
      // code goes here... 
    }()); 

This pattern is especially suitable for on-off initialization task, performed when the script loads.

The immediate self-executing function pattern can be extended to create and return objects. If the creation of these objects is more complicated and involves some initialization work, then you can do this in the first part of the self-executable function and return a single object that can access and benefit from any private properties at the top portion, as follows:

    var MYAPP = {}; 
    MYAPP.dom = (function () { 
      // initialization code... 
      function _private() { 
        // ...  
      } 
      return { 
        getStyle: function (el, prop) { 
          console.log('getStyle'), 
          _private(); 
        }, 
        setStyle: function (el, prop, value) { 
          console.log('setStyle'), 
        } 
      }; 
    }()); 

Modules

Combining several of the previous patterns gives you a new pattern, commonly referred to as a module pattern. The concept of modules in programming is convenient as it allows you to code separate pieces or libraries and combine them as needed, just like pieces of a puzzle.

The module pattern includes the following:

  • Namespaces to reduce naming conflicts among modules
  • An immediate function to provide a private scope and initialization
  • Private properties and methods

Note

ES5 doesn't have a built-in concept of modules. There is the module specification from http://www.commonjs.org, which defines a require() function and an exports object. ES6, however, supports modules. Chapter 8, Classes and Modules has covered modules in detail.

  • Returning an object that has the public API of the module as follows:
            namespace('MYAPP.module.amazing'), 
     
            MYAPP.module.amazing = (function () { 
     
              // short names for dependencies 
              var another = MYAPP.module.another; 
     
              // local/private variables 
              var i, j; 
     
              // private functions 
              function hidden() {} 
     
              // public API 
              return { 
                hi: function () { 
                  return "hello"; 
                } 
              }; 
            }()); 
    

And, you can use the module in the following way:

    MYAPP.module.amazing.hi(); // "hello" 

Chaining

Chaining is a pattern that allows you to invoke multiple methods on one line as if the methods are the links in a chain. This is convenient when calling several related methods. You invoke the next method on the result of the previous without the use of an intermediate variable.

Say you've created a constructor that helps you work with DOM elements. The code to create a new <span> tag that is added to the <body> tag can look something like the following:

    var obj = new MYAPP.dom.Element('span'), 
    obj.setText('hello'), 
    obj.setStyle('color', 'red'), 
    obj.setStyle('font', 'Verdana'), 
    document.body.appendChild(obj); 

As you know, constructors return the object referred to as this keyword that they create. You can make your methods, such as setText() and setStyle(), also return this keyword, which allows you to call the next method on the instance returned by the previous one. This way, you can chain method calls, as follows:

    var obj = new MYAPP.dom.Element('span'), 
    obj.setText('hello') 
       .setStyle('color', 'red') 
       .setStyle('font', 'Verdana'), 
    document.body.appendChild(obj); 

You don't even need the obj variable if you don't plan on using it after the new element has been added to the tree, so the code looks like the following:

    document.body.appendChild( 
      new MYAPP.dom.Element('span') 
        .setText('hello') 
        .setStyle('color', 'red') 
        .setStyle('font', 'Verdana') 
    );    

A drawback of this pattern is that it makes it a little harder to debug when an error occurs somewhere in a long chain, and you don't know which link is to blame because they are all on the same line.

JSON

Let's wrap up the coding patterns section of this chapter with a few words about JSON. JSON is not technically a coding pattern, but you can say that using it is a good pattern.

JSON is a popular lightweight format to exchange data. It's often preferred over XML when using XMLHttpRequest() to retrieve data from the server. There's nothing specifically interesting about JSON other than the fact that it's extremely convenient. The JSON format consists of data defined using object and array literals. Here is an example of a JSON string that your server can respond with after an XHR request:

    { 
      'name':   'Stoyan', 
      'family': 'Stefanov', 
      'books':  ['OOJS', 'JSPatterns', 'JS4PHP'] 
    } 

An XML equivalent of this will be something like the following piece of code:

    <?xml version="1.1" encoding="iso-8859-1"?> 
    <response> 
      <name>Stoyan</name> 
      <family>Stefanov</family> 
      <books> 
        <book>OOJS</book> 
        <book>JSPatterns</book> 
        <book>JS4PHP</book> 
      </books> 
    </response> 

First, you can see how JSON is lighter in terms of the number of bytes. However, the main benefit is not the smaller byte size, but the fact that it's trivial to work with JSON in JavaScript. Let's say, you've made an XHR request and have received a JSON string in the responseText property of the XHR object. You can convert this string of data into a working JavaScript object by simply using eval(). Consider the following example:

    // warning: counter-example 
    var response = eval('(' + xhr.responseText + ')'), 

Now, you can access the data in obj as object properties as follows:

    console.log(response.name); // "Stoyan" 
    console.log(response.books[2]); // "JS4PHP" 

The problem is that eval() is insecure, so it's best if you use the JSON object to parse the JSON data (a fallback for older browsers is available at http://json.org/). Creating an object from a JSON string is still trivial as follows:

    var response = JSON.parse(xhr.responseText); 

To do the opposite, that is, to convert an object to a JSON string, you can use the stringify() method, as follows:

    var str = JSON.stringify({hello: "you"}); 

Due to its simplicity, JSON has quickly become popular as a language-independent format to exchange data, and you can easily produce JSON on the server side using your preferred language. In PHP, for example, there are the json_encode() and json_decode() functions that let you serialize a PHP array or object into a JSON string, and vice versa.

Higher order functions

Functional programming was confined to a limited set of languages so far. With more languages adding features to support functional programming, interest in the area is gaining momentum. JavaScript is evolving to support common features of functional programming. You will gradually see a lot of code written in this style. It is important to understand the functional programming style, even if you don't feel inclined just yet to use it in your code.

Higher order functions are one of the important mainstays of functional programing. Higher order function is a function that does at least one of the following:

  • Takes one or more functions as arguments
  • Returns a function as a result

As functions are first class objects in JavaScript, passing and returning functions to and from a function is a pretty routine affair. Callbacks are higher order functions. Let's take a look at how we can take these two principles together and write a higher order function.

Let's write a filter function; this function filters out values from an array based on a criteria determined by a function. This function takes two arguments-a function, which returns a Boolean value, true for keeping this element.

For example, with this function, we are filtering all odd values from an array. Consider the following lines of code:

    console.log([1, 2, 3, 4, 5].filter(function(ele){
      return ele % 2 == 0; })); 
    //[2,4] 

We are passing an anonymous function to the filter function as the first argument. This function returns a Boolean based on a condition that checks if the element is odd or even.

This is an example of one of the several higher order functions added to ECMAScript 5. The point we are trying to make here is that you will increasingly see similar patterns of usage in JavaScript. You must first understand how higher order functions work and later, once you are comfortable with the concept, try to incorporate them in your code as well.

With ES6 function syntax changes, it is even more elegant to write higher order functions. Let's take a small example in ES5 and see how that translates into its ES6 equivalent:

    function add(x){ 
      return function(y){ 
        return y + x; 
      }; 
    } 
     var add3 = add(3); 
    console.log(add3(3));          // => 6 
    console.log(add(9)(10));       // => 19 

The add function takes x and returns a function that takes y as an argument and then returns value of expression y+x.

When we looked at arrow functions, we discussed that arrow functions return results of a single expression implicitly. So, the preceding function can be turned into an arrow function by making the body of the arrow function another arrow function. Take a look at the following example:

    const add = x => y => y + x; 

Here, we have an outer function, x => [inner function with x as argument], and we have an inner function, y => y+x.

This introduction will help you get familiar with the increasing usage of higher order functions, and their increased importance in JavaScript.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.68.14