Effective JavaScript Item 19 uses higher-order functions (High-order function)

Source: Internet
Author: User
Tags types of functions

this series as effective JavaScript 's reading notes.

Don't be fooled by the name of the higher-order function. In fact, higher-order functions represent only two types of functions:

    1. Functions that accept other functions as arguments
    2. Functions that return values as functions

With this definition, you may find that you have already used them, typically the callback functions that are passed in when handling some events.

Another typical use scenario is Array type of Sort function, which can accept a function as the basis for comparison when sorting:


[3, 1, 4, 1, 5, 9].sort (function (x, y) {if (x < y) {return-1;} if (x > Y) {return 1;} return 0;}); [1, 1, 3, 4, 5, 9]


use higher-order functions to make the code clearer and cleaner. You can consider using them when working with data for collection types, such as converting the following for loops:


var names = ["Fred", "Wilma", "pebbles"];var upper = [];for (var i = 0, n = names.length; i < n; i++) {Upper[i] = names [I].touppercase ();} Upper ["FRED", "WILMA", "Pebbles"]

Use ES5 introduced in the Map function:


var names = ["Fred", "Wilma", "pebbles"];var upper = Names.map (function (name) {return name.touppercase ();}); Upper ["FRED", "WILMA", "Pebbles"]

of course, in non- ES5 compatible Browser, if you want to use the Map and other high-order functions, you can use Underscore or Lodash . They provide a lot of action for Array,Object .

When there are a lot of duplicate fragments in the code, you can consider using higher-order functions to refactor them. For example, in the following code, there are three similar code, the first paragraph is used to generate the alphabet, the second is used to generate a number table, the last paragraph to generate a fixed length of random string:


var aindex = "a". charCodeAt (0); 97var alphabet = ""; for (var i = 0; I < 26; i++) {alphabet + = String.fromCharCode (Aindex + i);} Alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ" var digits = ""; for (var i = 0; I < 10; i++) {digits + = i;} Digits "0123456789" var random = ""; for (var i = 0; I < 8; i++) {random + = String.fromCharCode (Math.floor (Math.random () * +) + Aindex);} Random "BDWVFRTP" (different result each time)

you can encapsulate the different parts of the above three scenarios into a Callback , and then using a higher-order function to process, the higher-order function extracts the public parts of the three scenarios:


function buildstring (n, callback) {var result = ""; for (var i = 0; I < n; i++) {result + = callback (i);} return result;}

So the above three scenarios can be implemented as follows:


var alphabet = buildstring (+, function (i) {return String.fromCharCode (Aindex + i);}); Alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ" var digits = buildstring (ten, function (i) {return i;}); Digits "0123456789" var random = buildstring (8, function () {return String.fromCharCode (Math.floor (Math.random () *) + Aindex );}); Random "LTVISFJR" (different result each time)

It is clear that this implementation can cover more possibilities, because the parts of the change are used Callback be represented. At the same time, this approach also conforms to coding best practices, and when the loop part needs to change, you just need to modify one place.

Summarize:

  1. Higher-order functions are functions that tell other functions as parameters or return functions as return values
  2. Learn to use Map And other methods, learning to use Lodash or Underscore Library
  3. Discover duplicate code snippets in your code and refactor them using higher-order functions




Effective JavaScript Item 19 uses higher-order functions (High-order function)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.