Unlocking Functional Programming in JavaScript: Practical Tips & Code
This article explores the fundamentals and benefits of functional programming in JavaScript, showcases real‑world examples using plain functions, currying, Ramda, and RxJS, and highlights how these techniques improve code readability, composability, and maintainability for front‑end developers.
Functional Programming in JavaScript
Functional programming concepts were first introduced in the 1930s, but many engineers rarely use them. JavaScript, influenced by Lisp, treats functions as first‑class citizens and supports closures, making functional techniques naturally available.
Traditional computer‑science courses (discrete math, linear algebra) encourage imperative, instruction‑oriented coding. Before ES6, developers relied on prototypes; after ES6/TypeScript, classes became common. These approaches are machine‑friendly, while functional programming can offer a different perspective.
Why Try Functional Programming?
When solving a feature, functional thinking resembles solving a math problem: break down data transformations, search for existing utility functions, and write small, pure functions. Over time, developers adopt functional annotations and modularize code into clear, composable pieces.
Core functional concepts include category theory, first‑class functions, pure functions, composition, and currying.
Example: Currency Conversion
Suppose an API returns a list of products with prices in USD and we need to display them in the user's local currency.
{
"success": true,
"data": {
"name": "ProductsDetail",
"list": [
{ "name": "T shirt", "price": "10.00", "unit": "$" },
{ "name": "T shirt with logo", "price": "15.00", "unit": "$" },
{ "name": "T shirt with brand logo", "price": "20.00", "unit": "$" }
]
}
}
{
"userCurrency": "¥",
"userCurrencyRate": "6.5"
}A straightforward loop or Underscore.js could handle the conversion, but a functional approach emphasizes composition.
Simple Multiply Function
const multiply = function(x, y) {
return x * y;
};
multiply(3, 5); // 15Currying the Multiply Function
const multiply = function(x) {
return function(y) {
return x * y;
};
};
const multiply3 = multiply(3);
multiply3(5); // 15Using Ramda’s curry simplifies this pattern:
const R = require('ramda');
const multiply = function(x, y) {
return x * y;
};
const multiplyAutoCurry = R.curry(multiply);
multiplyAutoCurry(3)(5); // 15
multiplyAutoCurry(3, 5); // 15We can map the curried function over an array:
const R = require('ramda');
const multiply = function(x, y) { return x * y; };
const multiplyAutoCurry = R.curry(multiply);
const multiply3 = multiplyAutoCurry(3);
R.map(multiply3, [1, 2, 3]); // [3, 6, 9]Putting it all together for the currency conversion:
const R = require('ramda');
const multiply = function(x, y) { return x * y; };
const multiplyAutoCurry = R.curry(multiply);
const multiplyCurrency = multiplyAutoCurry(6.5);
const parseIntCurry = R.curry(parseInt);
const parseInt10 = parseIntCurry(R.__, 10);
const currencyConvert = R.compose(multiplyCurrency, parseInt10);
const result = {
success: true,
data: {
name: 'ProductsDetail',
list: [
{ name: 'T shirt', price: '10.00', unit: '$' },
{ name: 'T shirt with logo', price: '15.00', unit: '$' },
{ name: 'T shirt with brand logo', price: '20.00', unit: '$' }
]
}
};
const priceArray = R.pluck('price', R.prop('list', R.prop('data', result)));
R.map(currencyConvert, priceArray); // [65, 97.5, 130]Because price arrives as a string, we first convert it to a number (using parseInt with radix 10 for compatibility) before applying the composed conversion function.
Reactive Extensions (RxJS) Example
Functional streams are also central to RxJS. The following code creates a click counter that throttles events and accumulates clicks:
import { fromEvent } from 'rxjs';
import { throttleTime, scan } from 'rxjs/operators';
fromEvent(document, 'click')
.pipe(
throttleTime(1000),
scan(count => count + 1, 0)
)
.subscribe(count => console.log(`Clicked ${count} times`));At this year’s D2 Language & Framework session, RxJS lead Ben Lesh demonstrated how to shrink and speed up RxJS by leveraging modern JavaScript features.
TC39 Proposals Related to Functional Programming
pipeline operator
partial application
pattern matching
record & tuple
Igalia TC member Ujjwal also discussed new ES2020/ES2021 features that improve the JavaScript developer experience.
Conclusion
Functional programming is not a silver bullet, but in suitable scenarios it greatly simplifies code by turning data processing into pure, composable functions. Front‑end developers can enrich their toolbox with functional techniques, and you’ll see them reflected in libraries like React and RxJS.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
