Currying in JavaScript: Transforming Functions

Day 25: Currying in JavaScript 🍛 Currying sounds complicated… But it’s actually a powerful functional programming technique. 🔹 What is Currying? Currying is: Transforming a function that takes multiple arguments into a sequence of functions that take one argument at a time. Instead of this 👇 function add(a, b, c) { return a + b + c; } add(2, 3, 4); // 9 We do this 👇 function add(a) { return function (b) { return function (c) { return a + b + c; }; }; } add(2)(3)(4); // 9 One argument at a time 🔹 Why Use Currying? ✔ Improves reusability ✔ Helps create specialized functions ✔ Enables function composition ✔ Common in functional programming Real Practical Example function multiply(a) { return function (b) { return a * b; }; } const double = multiply(2); const triple = multiply(3); console.log(double(5)); // 10 console.log(triple(5)); // 15 Here: multiply(2) creates a reusable function That’s powerful abstraction 🔥Modern ES6 Version (Cleaner) const add = a => b => c => a + b + c; add(1)(2)(3); // 6 Short and elegant. 🔹 Currying vs Partial Application 👉 Currying → Always single argument functions 👉 Partial Application → Fix some arguments, not necessarily one by one Example of partial application: function add(a, b) { return a + b; } const add5 = add.bind(null, 5); console.log(add5(10)); // 15 🧠 Interview Insight Currying is possible in JavaScript because: ✔ Functions are first-class citizens ✔ Functions can return functions ✔ Closures preserve outer scope values 🔥 Where It’s Used? Redux Functional libraries like Lodash Middleware patterns Advanced React patterns #JavaScript #Currying #FunctionalProgramming #Frontend #WebDevelopment #LearnInPublic

To view or add a comment, sign in

Explore content categories