Open In App

What are Arguments in a Function ?

Arguments in JavaScript functions are the input values passed to the function when it is called. Functions can accept zero or more arguments, which can be used within the function body to perform specific tasks or calculations.

Uses of Arguments in Functions

Using named parameters:

You can specify the names of parameters explicitly in the function signature, allowing flexibility in the order of arguments when calling the function.



Example: Here we are passing “Geeks for Geeks!” as an argument in the function.




function greet(message) {
    console.log(`Hello, ${message}`);
}
greet("Geeks for Geeks!");

Output

Hello, Geeks for Geeks!

Using the arguments object:

JavaScript functions have access to an arguments object, which is an array-like object containing all the arguments passed to the function, regardless of how many arguments were specified in the function signature.

Example: Here we can access the argument property directly as it is built-in.




function sum() {
    let total = 0;
    for (let i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
}
console.log(sum(1, 2, 3));

Output
6

Using default parameters:

You can specify default values for function parameters, which will be used if no argument is provided when calling the function.

Example: Here we are setting default parameter so that if we does not provide argument it still print “name”.




function greet(name = "Geeks For Geeks") {
    console.log(`Hello, ${name}!`);
}
greet();
greet("User");

Output
Hello, Geeks For Geeks!
Hello, User!

Article Tags :