const - JS | lectureA Closer Look At Functions

Functions Returning Functions

A Closer Look At Functions

In this lecture, we will do the opposite of the last lecture and create a function that returns a new function. To demonstrate this point as easily as possible, I'm going to write a very simple greet function.

const greet = function (greeting) {
  return function (name) {    console.log(`${greeting} ${name}`);  };};

Let's call the greet function and pass it a greeting.


The result of calling the greet function is a function. This means we need to store the function in a variable.

const sayHello = greet('Hello');

Now , since sayHello is a function, we can call it just as if it was any other function that we defined ourselves.


Greet function result

From the above output, you can see that everything worked as expected. This worked because sayHello is the function returned by the greet function, which we are calling with the argument Ulrich.

Greet function flow

Now, the greeting value used in the returned function comes from the greet function param. And in case you're wondering why that actually works, it is because of something called a closure. Closures are a very complex and difficult-to-understand mechanism that's part of JavaScript.

Hence, there will be two separate lectures later about closures. It's one of the most misunderstood topics in JavaScript. So don't worry about that now. What matters here is that our first function, greet, returned a new function that we stored into the sayHello variable. Which then makes our sayHello variable a function that we can call.

We could also do it all in one go:

 * Doing greet('Hello') will return a function. And to call that function,
 * all we need to do is to add parentheses and provide the arguments.

This example might look a bit weird and unnecessary to you. Like, what's the point of having functions returning other functions? This will become extremely useful in some situations, especially if we're using a functional programming paradigm, which we might see. So please try to undertand this lecture.

To finish this lecture, let's rewrite the greet function using arrow functions.

const greetArrow = (greeting) => (name) => console.log(`${greeting} ${name}`);

It's short, simple, and clean but confusing. And that's why I wrote it using the traditional way at the beginning of this lecture. But in the end, it's just one arrow function returning another arrow function. I hope this lecture was clear to you. And if so, then let's move on to the next lecture.