DEV Community

Cover image for Higher order functions and closures example in Javascript
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

3

Higher order functions and closures example in Javascript

First with "normal" functions:

//closures and higher order function
function salute(salutation) {
  return function(firstName) {
    return function(lastName) {
      console.log(`hi ${salutation} ${firstName} ${lastName}`)
    }
  }
}

salute('Mr.')('John')('Wick')

//output
hi Mr. John Wick

Enter fullscreen mode Exit fullscreen mode

The shorter variant with arrow functions:

const saluteArrowFunction = (salutation) => (firstName) => (lastName) => console.log(`hi ${salutation} ${firstName} ${lastName}`);

saluteArrowFunction ('Mr.')('Johnny')('Cage')

//output
hi Mr. Johnny Cage
Enter fullscreen mode Exit fullscreen mode


Learn more about:

Shared with ❤️ from Codever.   👉   use the copy to mine functionality to add it to your personal snippets collection.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay