DEV Community

Cover image for Pass Arguments As An Object in JavaScript
Jennifer Bland
Jennifer Bland

Posted on • Originally published at jenniferbland.com on

Pass Arguments As An Object in JavaScript

When you learn to program in JavaScript, you learn to name the arguments that you pass into a function. I am going to show you why you should pass your arguments to a function as an object. Once you see why you will never go back to naming every argument you pass into a function. I promise you.

Example of naming arguments

I have a function called createBook. The function takes 6 arguments:

  • title
  • subtitle
  • author
  • publisher
  • datePublished
  • descr

Here is an example of my function and how you would call it:

const createBook = (title, subtitle, author, publisher, datePublished, descr) => {
  // code goes here
}

createBook('Make 7 Real World Apps in Vue 2', '', 'Jennifer Bland', 'Gumroad', '2022', 'Learn how to create 7 real world apps using Vue 2');
Enter fullscreen mode Exit fullscreen mode

If you were to look at this code, you would not have any idea what each of these arguments was much less know the correct order in which you have to enter them.

Passing Arguments As An Object

I can make your life easy by showing you how to pass arguments as an object. Here is what it looks like:

const createBook = ({ title, subtitle, author, publisher, datePublished, descr }) => {
    // code goes here
}

createBook({
    author: 'Jennifer Bland',
    publisher: 'Gumroad',
    title: 'Make 7 Real World Apps in Vue 2',
    descr: 'Learn how to create 7 real world apps using Vue 2',
    datePublished: '2022'
    subtitle: ''
});
Enter fullscreen mode Exit fullscreen mode

Now when you come across this code, it is clear what parameters are being passed to the function. Bonus: you don't have to worry about the order of the arguments since we are using destructuring in the function.

Buy My Book

I did write a book titled 'Make 7 Real World Apps in Vue 2'. If you are interested in reading it, you can get it on Gumroad.

Let's Connect

Thanks for reading my article today. If you like my content, please consider buying me a coffee ☕.

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay