Javascript Function arguments

Introduction

An Javascript function doesn't care how many arguments are passed in.

And it does care about the data types of those arguments.

If a function is defined to accept two arguments, you do not have to pass in only two arguments.

You could pass in one or three or none.

Arguments in Javascript are represented as an array internally.

The array is passed to the function.

The function doesn't care what is in the array.

When a function is defined using the function keyword, there is an arguments object that can be accessed.

We can use the arguments to retrieve the values of each argument that was passed in.

The arguments object acts like an array.

function sayHi(name, message) {
   console.log("Hello " + name + ", " + message);
}

The same value can be accessed by referencing arguments[0].

function sayHi() {
    console.log("Hello " + arguments[0] + ", " + arguments[1]);
}

Javascript function's named arguments are a convenience, not a necessity.

Arguments in Javascript does not create a function signature.

The arguments object can check the number of arguments passed into the function via the length property.

The following example outputs the number of arguments passed into the function:

function howManyArgs() {
    console.log(arguments.length);
}

howManyArgs("string", 42); // 2 
howManyArgs(); // 0 
howManyArgs(12); // 1 

The following function behave differently on argument length.

function doAdd() {
    if (arguments.length === 1) {
        console.log(arguments[0] + 10);
    } else if (arguments.length === 2) {
        console.log(arguments[0] + arguments[1]);
    }/*ww w.  j a  va  2  s .  co m*/
}

doAdd(10); // 20 
doAdd(30, 20); // 50 

The arguments object can work with named arguments:

function doAdd(num1, num2) {
    if (arguments.length === 1) {
        console.log(num1 + 10);
    } else if (arguments.length === 2) {
        console.log(arguments[0] + num2);
    }
}

Arguments' values stay in sync with the values of the corresponding named parameters.

function doAdd(num1, num2) {
    arguments[1] = 10;//  ww w  . j a v  a 2  s .  c om
    console.log(arguments[0] + num2);
}
console.log(doAdd(10));

The arrow function cannot access arguments.

function foo() {
    console.log(arguments[0]);
}
foo(5); // 5 

let bar = () => {
    console.log(arguments[0]);
};
bar(5); // ReferenceError: arguments is not defined 



PreviousNext

Related