How to use JavaScript Arguments? [SOLVED]


Written by - Olorunfemi Akinlua
Reviewed by - Deepak Prasad

Getting started with JavaScript Arguments

When we create functions, they may take in certain inputs that the code block within them works with to return values. These inputs are called arguments.

JavaScript deals with arguments in functions by adding them to a custom object called arguments. This object works a lot like an array, and we can use it instead of using the name of the parameter. Consider the following code:

function test(a, b, c) {
  console.log("first:", a, arguments[0]);
  console.log("second:", b, arguments[1]);
  console.log("third:", c, arguments[2]);
}
test("fun", "js", "secrets");

This outputs:

first: fun fun
second: js js
third: secrets secrets

When you update one of the parameters, the argument gets changed accordingly. The same goes for the other way around;

function test(a, b, c) {
  a = "nice";
  arguments[1] = "JavaScript";
  console.log("first:", a, arguments[0]);
  console.log("second:", b, arguments[1]);
  console.log("third:", c, arguments[2]);
}
test("fun", "js", "secrets");

This is going to change both arguments[0] and b, as they are related to a and arguments[1], respectively, as you can see in the output:

first: nice nice
second: JavaScript JavaScript
third: secrets secrets

If the function is called with more arguments than were declared in the function signature, this is the way to access them. However, the modern way is to use the rest parameter (…param) instead of the arguments object.

 

Working with arguments in JavaScript

Listing arguments

There are several ways to specify function arguments in JavaScript. The most common way is to list the arguments in the function definition, separated by commas.

function add(x, y) {
    return x + y;
}

In this example, the add function has two arguments: x and y. These arguments are used to perform the addition operation when the function is called.

Here's an example of how you might call the function above.

let result = add(2, 3);
console.log(result);

Output

5

 

Using the arguments object

You can also access function arguments using the arguments object, which is an array-like object that contains the values of all the arguments passed to the function. The arguments object is particularly useful when working with functions that can take a variable number of arguments, as it allows you to access all of the arguments passed to the function.

Let’s illustrate the use of the arguments object within JavaScript functions by passing multiple arguments to the sum() function, and then iterating over each to give the summation of the numbers.

function sum() {
    let total = 0;
    for (let i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
}

let result = sum(1, 2, 3, 4, 5);
console.log(result);

Output

15

In this example, the sum function uses the arguments object to iterate over all the arguments passed to the function and calculate their sum.

 

Using default values

You can also use default values for function arguments in case no value is passed to the function. Let’s use create a hello() function that takes a name argument but

function hello(name = "user") {
    console.log(`Hello, ${name}!`);
}

hello();
hello("David");

Output

Hello, user!
Hello, David!

In this example, the name argument has a default value of 'user'. If no value is passed to the greet function, it will use the default value. However, if a value is passed to the function, it will use that value instead of the default.

 

Rest Parameters and the Spread Operator

You can also use the spread operator (...) to pass an array of values as function arguments. Let’s illustrate the use of the spread operator with arrays by recreating the sum() method.

function sum(...numbers) {
    let total = 0;
    for (let i = 0; i < numbers.length; i++) {
        total += numbers[i];
    }
    return total;
}

let result = sum(...[1, 2, 3, 4, 5]);
console.log(result);

Output

15

In this example, the sum function uses the spread operator to destructure the array of numbers into individual arguments, which are then used to calculate the sum.

Many functions and methods accept variable arguments. For example, the Math.max method yields the largest of its arguments, no matter how many:

let result = Math.max(3, 1, 4, 1, 5, 9, 2, 6) // Sets result to 9

What if the values are already in an array?

let numbers = [1, 7, 2, 9]
result = Math.max(numbers) // Yields NaN

That doesn’t work. The Math.max method receives an array with one element - the array [1, 7, 2, 9].

Instead, use the “spread” operator - the ... token placed before an array argument:

result = Math.max(...numbers) // Yields 9

The spread operator spreads out the elements as if they had been provided separately in the call.

NOTE:
Even though the spread operator and rest declaration look the same, their actions are the exact opposites of each other.

First, note that the spread operator is used with an argument, and the rest syntax applies to a variable declaration.

Math.max(...numbers) // Spread operator argument in function call
const max = (...values) => { /* body */}  // Rest declaration of parameter variable

The spread operator turns an array (or, in fact, any iterable) into a sequence of values. The rest declaration causes a sequence of values to be placed into an array.

 

Summary

Function arguments are an important part of JavaScript programming, as they allow you to pass values to functions and perform operations on them. By understanding how to use different types of arguments, you can write more flexible and powerful functions. From using spread operators to the arguments object, arguments are easy to use and make functions powerful.

 

References

The arguments object - JavaScript | MDN (mozilla.org)
Functions - JavaScript | MDN (mozilla.org)

 

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment