DEV Community

Discussion on: Function Currying in JavaScript

Collapse
 
derekenos profile image
Derek Enos • Edited

Here's an example of a console.log() helper, a variation of which I've used in production code and is pretty much identical to @afrazchelsea 's greet() example, that allows you to specify a scope name that it'll use to prefix each message.

Without currying, the function would look like this:

const scopedLogger = (scope, msg) => console.log(`[${scope}]: ${msg}`)

Requiring you to specify scope on every call:

>> scopedLogger('MAIN', "test main")
[MAIN]: test main

This curried version of the function accepts the single argument scope, and returns a second function that accepts the single argument msg:

const scopedLogger = scope => msg => console.log(`[${scope}]: ${msg}`)

This allows you to create pre-scoped logger functions for which you only have to specify msg:

const mainLogger = scopedLogger('MAIN')
const debugLogger = scopedLogger('DEBUG')
>> mainLogger("test main")
[MAIN]: test main

>> debugLogger("test debug")
[DEBUG]: test debug

For reference, here's the normal function / non-arrow-function version of that curried scopedLogged() function:

function scopedLogger (scope) {
  function f (msg) {
    console.log(`[${scope}]: ${msg}`)
  }
  return f
}

which works the same way:

>> const mainLogger = scopedLogger('MAIN')
>> mainLogger("test main")
[MAIN]: test main
Collapse
 
afrazchelsea profile image
Afraz Momin

Amazing @derekenos , thank you!

Collapse
 
lagsurfer profile image
Barney

I see I see. Thanks for the great example.