Home > Web Front-end > JS Tutorial > How Does Currying Work with Multiple Arrow Functions in JavaScript?

How Does Currying Work with Multiple Arrow Functions in JavaScript?

Linda Hamilton
Release: 2024-12-21 06:48:12
Original
382 people have browsed it

How Does Currying Work with Multiple Arrow Functions in JavaScript?

Currying with Multiple Arrow Functions in JavaScript

You may encounter code like this in React applications:

handleChange = field => e => {
  e.preventDefault();
  /// Do something here
}
Copy after login

This puzzling syntax represents what's known as a curried function.

What is Currying?

Currying is a technique that allows a function to be defined in parts. For example:

const add = x => y => x + y
Copy after login

This is equivalent to the traditional function:

const add = function (x) {
  return function (y) {
    return x + y
  }
}
Copy after login

Focusing on the Return Value

In arrow functions, the return value is represented as:

const f = someParam => returnValue
Copy after login

Therefore, our add function returns a function:

const add = x => (y => x + y)
Copy after login

Calling the function:

add(2)(3)  // returns 5
Copy after login

This occurs because the outer function call returns the inner function.

Understanding the handleChange Code

Applying this to the handleChange code:

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
  };
};
Copy after login

Because arrow functions preserve context, it effectively looks like:

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
  }.bind(this)
}.bind(this)
Copy after login

This code creates a function for a specific field. In React, it's used to set up listeners for various input fields without duplicating code.

Multiple Arrow Functions

Multiple arrow functions can be sequenced, allowing for surprising functionality like this:

const $ = x => k =>
  $ (k(x))
Copy after login

This curried function, called $ (as a pun on Lisp syntax), appears to accept an arbitrary number of arguments, abstracting the concept of arity.

The above is the detailed content of How Does Currying Work with Multiple Arrow Functions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template