Categories
JavaScript Answers

How to write nested functions in JavaScript?

Spread the love

Sometimes, we want to write nested functions in JavaScript.

In this article, we’ll look at how to write nested functions in JavaScript.

How to write nested functions in JavaScript?

To write nested functions in JavaScript, we can define functions inside functions.

For instance, we write

const a = (x) => {
  const b = (y) => {
    return x + y;
  };
  return b;
};
console.log(a(3)(4));

to define function b in function a.

We return function b in the last line of a.

And then we call a with 3 to return b.

Then we call b with 4 to get 7.

Conclusion

To write nested functions in JavaScript, we can define functions inside functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *