Câu hỏi phỏng vấn Javascript
Câu hỏi

What is Currying in javascript?

Câu trả lời

Currying in JavaScript is a transformative technique in functional programming where a function that normally takes multiple arguments is converted into a sequence of functions, each taking a single argument. This process continues until all arguments have been provided, ultimately resulting in the execution of the original function.

Definition and Basic Concept

Currying is named after the mathematician Haskell Curry. The essence of currying is to break down a function that takes multiple arguments into a series of functions that each take only one argument. For instance, a function that takes three arguments, like sum(a, b, c), would be transformed into sum(a)(b)(c).

How Currying Works

In JavaScript, currying is implemented by returning a new function from the current function, capturing a provided argument, and waiting for the next arguments to be fulfilled. This is achieved using closures, where each returned function has access to the arguments of its parent functions due to JavaScript's lexical scoping.

Example of Currying

Here's a simple example to illustrate currying:

function sum(a) {
    return function(b) {
        return function(c) {
            return a + b + c;
        };
    };
}
console.log(sum(1)(2)(3)); // Outputs 6

In this example, sum is a curried function that takes one argument at a time. Each function call returns a new function that takes the next argument until all arguments are provided, culminating in the sum of all arguments.

Practical Uses of Currying

Currying can be particularly useful in scenarios where you need to set up functions with predefined arguments which you can reuse later. This can lead to more readable and maintainable code, especially in complex applications. It also allows for easy function composition and partial application, where a function that takes multiple arguments can be transformed into a function that takes fewer arguments, with some arguments preset.

Advantages of Currying

  1. Reusability: Curried f...
middle

middle

Gợi ý câu hỏi phỏng vấn

expert

What's the difference between ES6 Map and WeakMap ?

junior

Is there anyway to force using strict mode in Node.js?

middle

Explain Function.prototype.bind .

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào