support@90-10.dev

The Magic of JavaScript Function Arguments Object

A special arguments object holds a list of all arguments passed to a JavaScript function even if none are specified in its definition. And can be used in creative ways! 😉

Defining a "regular" function

A function is usually defined via the function keyword with arguments, if required, specified in following parenthesis. In the example below we've defined a sayHello function with 2 parameters:

function sayHello(name, business) {
  console.log(`Hello ${name} from ${business}!`);
}
sayHello("Paul", "90-10.dev"); // "Hello Paul from 90-10.dev!"

Inside the function, parameters are accessed via their names given in the function definition, name & business in our case.

arguments object

There is however another way to access any data passed onto the function, via the special arguments object where any passed on data is stored:

function sayHello() {
  console.log(arguments);
}
sayHello("Paul", "90-10.dev");

The console will show:

Arguments { 0: "Paul", 1: "90-10.dev", ... }

And we can check if indeed arguments is an object:

console.log(typeof arguments); // object

... and we can check how many were passed and even list all arguments:

function sayHello() {
  console.log(arguments.length);
  for(let arg of arguments) {
    console.log(arg);
  }
}

Using arguments

Arguments can be accessed in an array-like fashion using indices:

function sayHello() {
  console.log(`Hello ${arguments[0]} from ${arguments[1]}!`);
}
sayHello("Paul", "90-10.dev"); // "Hello Paul from 90-10.dev!"

Modifying arguments

Arguments can also be modified on the fly:

function sayHello() {
  arguments[0] = "World";
  console.log(`Hello ${arguments[0]} from ${arguments[1]}!`);
}
sayHello("Paul", "90-10.dev"); // "Hello World from 90-10.dev!"

That's it! Happy Hacking!