Categories
JavaScript Answers

How to add named function parameters with JavaScript?

Spread the love

Sometimes, we want to add named function parameters with JavaScript.

In this article, we’ll look at how to add named function parameters with JavaScript.

How to add named function parameters with JavaScript?

To add named function parameters with JavaScript, we can make a function accept an object as a parameter.

Then we can destructure the object’s properties into variables.

For instance, we write:

const callApi = ({
  url,
  callback,
  query = {},
  body = {}
}) => {

}

callApi({
  url: "/api/..",
  callback: (x => console.log(x)),
  body: {
    a: 2
  }
})

We have the callApi function that takes an object with the url, callback, query and body properties.

We set the default value of query and body to an empty when it’s not set.

Then we call it with an object with those properties set.

Conclusion

To add named function parameters with JavaScript, we can make a function accept an object as a parameter.

Then we can destructure the object’s properties into variables.

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 *