Follow Us:
Javascript /

Passing an object as an argument to a function

Created Date: 24th March, 2023
Updated Date: 13th April, 2023

In programming languages, functions play a vital role in making the code reusable and implementing the concept of DRY (Don't Repeat Yourself).

Functions are blocks of code that perform a specific task and can be invoked multiple times from different parts of the code.

One of the essential aspects of functions is the ability to pass arguments, which are values or objects that the function uses to perform its task. In this post, we will discuss how to pass an object as an argument in a function.

Passing Arguments in Functions: In JavaScript, we can define a function with arguments as below:

function user_information(name, age, skills = null)(){
    return "Hello " + name + "your age is " + age + "and your skills are " + skills
}

To call the function we pass the arguments in the same order as they appear in the function definition:

console.log(user_information("John",30,['HTML', 'CSS', 'JavaScript']));

The function mentioned above returns the name, age, and user skills. However, a notable limitation of this function is the necessity to define the arguments in a particular order

Passing Objects as Arguments:

A solution to overcome the constraint of defining arguments in a specific order is to pass an object as an argument. This approach allows us to define arguments in any desired order while maintaining full control over them. The code snippet below demonstrates this:

function user_information(args){
    
    let defaults = {
        name:null,
        age:0,
        skills:[]
    }

    let params = {...defaults, ...args}; 


    return "Hello " + params.name + "your age is " + params.age + "and your skills are " + params.skills
    
}

In the provided code, the function is defined with a single argument, 'args', which represents an object. Default values are assigned to the object properties. Subsequently, the 'args' object is merged with the 'defaults' object, creating a new object called 'params'. This 'params' object contains all properties along with their corresponding values.

To call the function, we pass an object with the arguments in any order we want:

console.log(user_information({
    name:"John",
    skills: ["HTML", "CSS", "JavaScript"],
    age:30
}))

The above function call will give us the flexibility to define the arguments in any order, making our code more organized and readable.

Passing objects as arguments in functions is a useful technique to improve code readability and organization. Many ready-made libraries use this technique to make their APIs more user-friendly. 

Share the post:

Tags:
function
array
object