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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more