Open In App

What are Arguments in a Function ?

Last Updated : 14 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  • Arguments allow functions to be customized for different scenarios by passing different values.
  • Functions can be made more flexible by accepting arguments, enabling them to handle various inputs.
  • Functions with arguments promote abstraction by encapsulating functionality that can be reused with different data.

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.

JavaScript
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.

JavaScript
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".

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

Output
Hello, Geeks For Geeks!
Hello, User!

Next Article
Article Tags :

Similar Reads