DEV Community

Cover image for A better way to pass parameters to functions
Arno Solo
Arno Solo

Posted on

3 1

A better way to pass parameters to functions

Original link

If a function requires 4 arguments, then we need to pass in 4 arguments, even if the middle argument is not needed in some cases. So can you pass in a few parameters if you need a few parameters? Yes, you will know after reading this article.

// πŸ‘Ž Ordinary way of passing parameters
printTodo('Learn Swift', undefined, undefined, ['learning']);
Enter fullscreen mode Exit fullscreen mode
// πŸ‘ Pass in only the parameters needed
printTodo({title: 'Learn Swift', tags: ['learning']});
Enter fullscreen mode Exit fullscreen mode

Ordinary way

function printTodo(
    title = 'Untitled',
    content = '',
    isDone = false,
    tags: string[] = [],
) {
    console.log(`Title: ${title}`);
    console.log(`Content: ${content}`);
    console.log(`Tags: ${tags.map(tag => `#${tag} `).join()} \n`);
}

printTodo('Learn Swift', undefined, undefined, ['learning']);
Enter fullscreen mode Exit fullscreen mode

Pass in only the parameters needed

interface Todo {
    title?: string;
    content?: string;
    isDone?: boolean;
    tags?: string[];
}

function printTodo({
    title = 'Untitled',
    content = '',
    isDone = false,
    tags = [],
}: Todo = {}) {
    console.log(`Title: ${title}`);
    console.log(`Content: ${content}`);
    console.log(`Tags: ${tags.map(tag => `#${tag} `).join()} \n`);
}

printTodo({title: 'Learn Swift', tags: ['learning']});
printTodo();

Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

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

Okay