Home Web Front-end JS Tutorial Basic Guide to Functional Programming in JavaScript_Basics

Basic Guide to Functional Programming in JavaScript_Basics

May 16, 2016 pm 03:10 PM
javascript js function Functional

Introduction

JavaScript is a powerful, yet misunderstood programming language. Some people like to say that it is an object-oriented programming language, or that it is a functional programming language. Others like to say that it is not an object-oriented programming language, or that it is not a functional programming language. Others think that it has characteristics of both an object-oriented language and a functional language, or that it is neither object-oriented nor functional. Well, let's put those arguments aside for now.

Let us assume that we share a mission: to write programs using as many functional programming principles as possible within the scope of the JavaScript language.

First of all, we need to clear up those misconceptions about functional programming in our minds.

Functional programming that is (severely) misunderstood in the JS world

Apparently there are quite a few developers who use JavaScript in a functional paradigm all day long. I would still say that there are a larger number of JavaScript developers who don't really understand the true meaning of that pretense.

I am convinced that this situation is caused by the fact that many web development languages ​​​​used on the server side are derived from C language, and C language is obviously not a functional programming language.

There seem to be two levels of confusion. Let’s use the following example that is often used in jQuery to illustrate the first level of confusion:

$(".signup").click(function(event){
  $("#signupModal").show();
  event.preventDefault();
});
Copy after login

Hey, look carefully. I pass an anonymous function as a parameter, which is known in the JavaScript world as a "CallBack" function.

Does anyone really think this is functional programming? Not at all!

This example demonstrates a key feature of functional languages: functions as parameters. On the other hand, this 3-line example also goes against almost every other functional programming paradigm.

The second level of chaos is a little more subtle. After reading this, some trend-seeking JS developers are thinking secretly.

Okay, crap! But I already know everything there is to know about functional programming. I use Underscore.js on all my projects.

Underscore.js is a popular JavaScript library used everywhere. For example, I have a set of words, and I need to get a set where each element in the set is the first two letters of each word. Implementing this with Underscore.js is fairly simple:

var firstTwoLetters = function(words){
  return _.map(words,function(word){
    return _.first(word,2);
  });
};
Copy after login

Look! See JavaScript Wizardry. I'm using these advanced functional application functions like _.map and _.first. Is there anything else you want to say, Leland?

Although highlights and functions like _.map are very valuable pieces of the functional paradigm, the way the code is organized like the one used in this example seems... verbose and too difficult for me to understand. Do we really need to do this?

If we start thinking with a little more "functional" thinking, maybe we can change the above example to this:

// ...一点魔法
var firstTwoLetters = map(first(2));
Copy after login

Think about it carefully, one line of code contains the same information as the five lines of code above. words and word are just parameters/placeholders. The core of this method is to combine the map function, the first function, and the constant 2 in a more obvious way.

Is JavaScript a functional programming language?

There is no magic formula to determine whether a language is a "functional" language. Some languages ​​are clearly functional, just as other languages ​​are clearly not functional, but there are plenty of languages ​​that fall somewhere in the ambiguous middle.

So here are some commonly used and important "ingredients" of functional languages ​​(JavaScript can use bold symbols)

  • Functions are “first class citizens”
  • Functions can return functions
  • Lexically supports closures
  • Functions must be “pure”
  • Reliable Recursion
  • No mutation status

This is by no means an exclusive list, but we will at least discuss one by one the three most important features of Javascript that enable us to write programs in a functional way.

Let’s take a closer look at each one:

Functions are “first class citizens”

This one is probably the most obvious of all ingredients, and probably the most common in many modern programming languages.

Local variables in JavaScript are defined through the var keyword.

var foo = "bar";
Copy after login

It is very easy to define functions as local variables in JavaScript.

var add = function (a, b) { return a + b; };
var even = function (a) { return a % 2 === 0; };
Copy after login

These are all facts, variables: variable add and variable even establish a reference relationship with the function definition by being assigned a value. This reference relationship can be changed at any time if necessary.

// capture the old version of the function
var old_even = even; 
 
// assign variable `even` to a new, different function
even = function (a) { return a & 1 === 0; };
Copy after login

Of course, this is nothing special. But the important feature of being a "first-class citizen" allows us to pass a function to another function as a parameter. For example:

var binaryCall = function (f, a, b) { return f(a, b); };
Copy after login

这是一个函数,他接受了一个二元函数f,和两个参数a,b,然后调用这个二元函数f,该二元函数f以a、b为输入参数。

add(1,2) === binaryCall(add, 1, 2); 
// true
Copy after login

这样做看起来有点笨拙,但是当把接下来的函数式编程“配料”合并考虑的时候,牛叉之处就显而易见了…

函数能返回函数(换个说法“高阶函数”)

事情开始变的酷起来。尽管开始比较简单。函数最终以新的函数作为返回值。举个例子:

var applyFirst = function (f, a) { 
 return function (b) { return f(a, b); };
};
Copy after login

这个函数(applyFirst)接受一个二元函数作为其中一个参数,可以把第一个参数(即二元函数)看作是这个applyFirst函数的“部分操作”,然后返回一个一元(一个参数)函数,该一元函数被调用的时候返回外部函数的第一个参数(f)的二元函数f(a, b)。返回两个参数的二元函数。

让我们再谈谈一些函数,例如mult(乘法)函数:

var mult = function(a, b) { return a * b; };
Copy after login

依循mult(乘法)函数的逻辑,我们可以写一个新的函数double(乘方):

var double = applyFirst(mult, 2);
 
double(32); 
// 64
double(7.5); 
// 15
Copy after login

这就是偏函数,在FP中经常会用到。(译注:FP全名为 Functional Programming 函数式程序设计 )

我们当然可以像applyFirst那样定义函数:

var curry2 = function (f) {
 return function (a) {
  return function (b) {
   return f(a, b);
  };
 };
};
Copy after login

现在,我想要一个double(乘方)函数,我们换种方式做:

var double = curry2(mult)(2);
Copy after login

这种方式被称作“函数柯里化”。有点类似partial application(偏函数应用),但是更强大一点。

准确的说,函数式编程之所以强大,大部分因于此。简单和易理解的函数成为我们构筑软件的基础构件。当拥有高水平的组织能力、很少重用的逻辑的时候,函数能够被组合和混合在一起用来表达出更复杂的行为。

高阶函数可以得到的乐趣更多。让我们看两个例子:

1.翻转二元函数参数顺序

// flip the argument order of a function
var flip = function (f) {
 return function (a, b) { return f(b, a); };
};
 
divide(10, 5) === flip(divide)(5, 10); 
// true
Copy after login

2.创建一个组合了其他函数的函数

// return a function that's the composition of two functions...
// compose (f, g)(x) -> f(g(x))
var compose = function (f1, f2) {
 return function (x) {
  return f1(f2(x));
 };
};
 
// abs(x) = Sqrt(x^2)
var abs = compose(sqrt, square);
 
abs(-2); 
// 2
Copy after login

这个例子创建了一个实用的函数,我们可以使用它来记录下每次函数调用。

var logWrapper = function (f) {
 return function (a) {
  console.log('calling "' + f.name + '" with argument "' + a);
  return f(a);
 };
};

var app_init = function(config) { 
/* ... */
 };
 
if(DEBUG) {
 
// log the init function if in debug mode
 app_init = logWrapper(app_init);
}
 
// logs to the console if in debug mode
app_init({
 
/* ... */
});

Copy after login

词法闭包+作用域

我深信理解如何有效利用闭包和作用域是成为一个伟大JavaScript开发者的关键。
那么…什么是闭包?

简单的说,闭包就是内部函数一直拥有父函数作用域的访问权限,即使父函数已经返回。<译注4>
可能需要个例子。

var createCounter = function () {
 var count = 0;
 return function () {
  return ++count;
 };
};
 
var counter1 = createCounter();
 
counter1(); 
// 1
counter1(); 
// 2
 
var counter2 = createCounter();
 
counter2(); 
// 1
counter1(); 
// 3
Copy after login

一旦createCounter函数被调用,变量count就被分配一个新的内存区域。然后,返回一个函数,这个函数持有对变量count的引用,并且每次调用的时候执行count加1操作。

注意从createCounter函数的作用域之外,我们是没有办法直接操作count的值。Counter1和Counter2函数可以操作各自的count变量的副本,但是只有在这种非

常具体的方式操作count(自增1)才是被支持的。

在JavaScript,作用域的边界检查只在函数被声明的时候。逐个函数,并且仅仅逐个函数,拥有它们各自的作用域表。(注:在ECMAScript 6中不再是这样,因为let的引入)

一些进一步的例子来证明这论点:

// global scope
var scope = "global";
 
var foo = function(){
 
// inner scope 1
 var scope = "inner";
 var myscope = function(){
  
// inner scope 2
  return scope;
 };
 return myscope;
};
 
console.log(foo()()); 
// "inner"
 
console.log(scope); 
// "global"
Copy after login

关于作用域还有一些重要的事情需要考虑。例如,我们需要创建一个函数,接受一个数字(0-9),返回该数字相应的英文名称。

简单点,有人会这样写:

// global scope...
var names = ['zero','one','two','three','four','five','six','seven','eight','nine'];
var digit_name1 = function(n){
 return names[n];
};
Copy after login

但是缺点是,names定义在了全局作用域,可能会意外的被修改,这样可能致使digit_name1函数所返回的结果不正确。
那么,这样写:

var digit_name2 = function(n){
 var names = ['zero','one','two','three','four','five','six','seven','eight','nine'];
 return names[n];
};
Copy after login

这次把names数组定义成函数digit_name2局部变量.这个函数远离了意外风险,但是带来了性能损失,由于每次digit_name2被调用的时候,都将重新为names数组定义和分配空间。换个例子如果names是个非常大的数组,或者可能digit_name2函数在一个循环中被调用多次,这时候性能影响将非常明显。

// "An inner function enjoys that context even after the parent functions have returned."
var digit_name3 = (function(){
 var names = ['zero','one','two','three','four','five','six','seven','eight','nine'];
 return function(n){
  return names[n];
 };
})();
Copy after login

这时候我们面临第三个选择。这里我们实现立即调用的函数表达式,仅仅实例化names变量一次,然后返回digit_name3函数,在 IIFE (Immediately-Invoked-Function-Expression 立即执行表达式)的闭包函数持有names变量的引用。
这个方案兼具前两个的优点,回避了缺点。搞定!这是一个常用的模式用来创建一个不可被外部环境修改“private”(私有)状态。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles