Skip to content

JavaScript Arguments

  • by

In JavaScript, the arguments object is a special object available inside every function that contains an array-like list of the arguments passed to that function. It allows you to access and manipulate the parameters that were passed to the function, regardless of the number of arguments or their data types.

function greet(name) {
  console.log('Hello ' + name + '!');
}

Here, name is a named parameter that can be accessed directly inside the function body. However, if you were to call this function with additional arguments, like this:

greet('Alice', 'Bob');

The additional argument ‘Bob’ would be ignored, because there is no corresponding parameter in the function definition. However, you can still access this argument using the arguments object:

function greet(name) {
  console.log('Hello ' + arguments[0] + '!');
}
greet('Alice', 'Bob'); // Output: 'Hello Alice!'

The arguments object is a local variable available inside all functions that contain a list of the arguments passed to the function. It allows you to access and manipulate the parameters that were passed to the function, regardless of the number of arguments or their data types.

JavaScript arguments example

Simple example code and common uses of the arguments object:

Accessing function arguments: You can use the arguments object to access the values of the parameters passed to a function, even if the number of arguments is not known in advance

function addNumbers() {
  var sum = 0;
  for (var i = 0; i < arguments.length; i++) {
    sum += arguments[i];
  }
  return sum;
}
console.log(addNumbers(1, 2, 3)); // Output: 6
console.log(addNumbers(1, 2, 3, 4, 5)); // Output: 15

Output:

JavaScript Arguments

Using the arguments object to create a variable number of parameters: You can use the arguments object to create functions that accept a variable number of arguments.

function concatenateStrings() {
  var result = '';
  for (var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}
console.log(concatenateStrings('Hello', ' ', 'World')); 
// Output: 'Hello World'

console.log(concatenateStrings('JavaScript', ' ', 'is', ' ', 'awesome')); 
// Output: 'JavaScript is awesome'

Modifying function arguments: You can modify the values of the arguments passed to a function using the arguments object. For example:

function doubleNumbers() {
  for (var i = 0; i < arguments.length; i++) {
    arguments[i] *= 2;
  }
  return arguments;
}
console.log(doubleNumbers(1, 2, 3)); 
// Output: [2, 4, 6]

console.log(doubleNumbers(4, 5, 6, 7)); 
// Output: [8, 10, 12, 14]

Comment if you have any doubts or suggestions on this Basic JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading