Javascript get argument function

Getting all arguments passed into a function with vanilla JavaScript

Today, I wanted to show you a super useful trick for getting all arguments passed into a function, whether you setup named variables for them or not.

The arguments variable

Within any function, you can use the arguments variable to get an array-like list of all of the arguments passed into the function.

Here’s the function we used last week to add two numbers together.

var add = function (num1, num2)  // If num1 or num2 aren't defined, set them to 0 num1 = num1 || 0; // conditional operator num2 = num2 ? num2 : 0; // ternary operator // Add the numbers return num1 + num2; >; 

You could also write it this way.

var add = function (num1, num2)  // If num1 or num2 aren't defined, set them to 0 arguments[0] = arguments[0] || 0; // conditional operator arguments[1] = arguments[1] ? arguments[1] : 0; // ternary operator // Add the numbers return arguments[0] + arguments[1]; >; 

When to use this

The arguments variable has limited use when you have a handful of arguments of differing values and types.

But, if you wanted to accept a non-specific number of arguments of a similar type, it’s very useful.

Let’s look at our add() function for a minute.

First, we can completely eliminate the need to name arguments in our function.

var add = function ()  // If num1 or num2 aren't defined, set them to 0 arguments[0] = arguments[0] || 0; // conditional operator arguments[1] = arguments[1] ? arguments[1] : 0; // ternary operator // Add the numbers return arguments[0] + arguments[1]; >; 

That’s cool, but not particularly useful. If anything, our code is more verbose.

A more useful application of the arguments variable here would be to let us pass in any amount of numbers to add together instead of just two.

To handle this, we’ll setup a starting number of 0 . Then, we’ll loop through the arguments array and add it to this number, and return the total at the end. This also eliminates the need for default variable values.

var add = function ()  var total = 0; for (var i = 0; i  arguments.length; i++)  total += arguments[i]; > return total; >; // Returns 1 add(1); // Returns 6 add(1, 2, 3); // Returns 0 add(); 

Tomorrow, we’ll look at how to use the arguments value but also accept an optional boolean as the first argument.

Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. Join over 14k others.

Made with ❤️ in Massachusetts. Unless otherwise noted, all code is free to use under the MIT License. I also very irregularly share non-coding thoughts.

Источник

The arguments object

arguments is an array-like object accessible inside functions that contains the values of the arguments passed to that function.

Try it

Description

Note: In modern code, rest parameters should be preferred.

The arguments object is a local variable available within all non-arrow functions. You can refer to a function’s arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry’s index at 0 .

For example, if a function is passed 3 arguments, you can access them as follows:

[0]; // first argument arguments[1]; // second argument arguments[2]; // third argument 

The arguments object is useful for functions called with more arguments than they are formally declared to accept, called variadic functions, such as Math.min() . This example function accepts any number of string arguments and returns the longest one:

function longestString()  let longest = ""; for (let i = 0; i  arguments.length; i++)  if (arguments[i].length > longest.length)  longest = arguments[i]; > > return longest; > 

You can use arguments.length to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function’s length property.

Assigning to indices

Each argument index can also be set or reassigned:

Non-strict functions that only has simple parameters (that is, no rest, default, or destructured parameters) will sync the new value of parameters with the arguments object, and vice versa:

function func(a)  arguments[0] = 99; // updating arguments[0] also updates a console.log(a); > func(10); // 99 function func2(a)  a = 99; // updating a also updates arguments[0] console.log(arguments[0]); > func2(10); // 99 

Non-strict functions that are passed rest, default, or destructured parameters will not sync new values assigned to parameters in the function body with the arguments object. Instead, the arguments object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called.

function funcWithDefault(a = 55)  arguments[0] = 99; // updating arguments[0] does not also update a console.log(a); > funcWithDefault(10); // 10 function funcWithDefault2(a = 55)  a = 99; // updating a does not also update arguments[0] console.log(arguments[0]); > funcWithDefault2(10); // 10 // An untracked default parameter function funcWithDefault3(a = 55)  console.log(arguments[0]); console.log(arguments.length); > funcWithDefault3(); // undefined; 0 

This is the same behavior exhibited by all strict-mode functions, regardless of the type of parameters they are passed. That is, assigning new values to parameters in the body of the function never affects the arguments object, nor will assigning new values to the arguments indices affect the value of parameters, even when the function only has simple parameters.

Note: You cannot write a «use strict»; directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw a syntax error.

arguments is an array-like object

arguments is an array-like object, which means that arguments has a length property and properties indexed from zero, but it doesn’t have Array ‘s built-in methods like forEach() or map() . However, it can be converted to a real Array , using one of slice() , Array.from() , or spread syntax.

const args = Array.prototype.slice.call(arguments); // or const args = Array.from(arguments); // or const args = [. arguments]; 

For common use cases, using it as an array-like object is sufficient, since it both is iterable and has length and number indices. For example, Function.prototype.apply() accepts array-like objects.

function midpoint()  return ( (Math.min.apply(null, arguments) + Math.max.apply(null, arguments)) / 2 ); > console.log(midpoint(3, 1, 4, 1, 5)); // 3 

Properties

Reference to the currently executing function that the arguments belong to. Forbidden in strict mode.

The number of arguments that were passed to the function.

Returns a new Array iterator object that contains the values for each index in arguments .

Examples

Defining a function that concatenates several strings

This example defines a function that concatenates several strings. The function’s only formal argument is a string containing the characters that separate the items to concatenate.

function myConcat(separator)  const args = Array.prototype.slice.call(arguments, 1); return args.join(separator); > 

You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:

myConcat(", ", "red", "orange", "blue"); // "red, orange, blue" myConcat("; ", "elephant", "giraffe", "lion", "cheetah"); // "elephant; giraffe; lion; cheetah" myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"); // "sage. basil. oregano. pepper. parsley" 

Defining a function that creates HTML lists

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is «u» if the list is to be unordered (bulleted), or «o» if the list is to be ordered (numbered). The function is defined as follows:

You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:

Using typeof with arguments

The typeof operator returns ‘object’ when used with arguments

.log(typeof arguments); // 'object' 

The type of individual arguments can be determined by indexing arguments :

.log(typeof arguments[0]); // returns the type of the first argument 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 5, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Function.prototype.arguments

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Note: The arguments property of Function objects is deprecated. The recommended way to access the arguments object is to refer to the variable arguments available within functions.

The arguments accessor property of Function instances returns the arguments passed to this function. For strict, arrow, async, and generator functions, accessing the arguments property throws a TypeError .

Description

The value of arguments is an array-like object corresponding to the arguments passed to a function.

In the case of recursion, i.e. if function f appears several times on the call stack, the value of f.arguments represents the arguments corresponding to the most recent invocation of the function.

The value of the arguments property is normally null if there is no outstanding invocation of the function in progress (that is, the function has been called but has not yet returned).

Note that the only behavior specified by the ECMAScript specification is that Function.prototype has an initial arguments accessor that unconditionally throws a TypeError for any get or set request (known as a «poison pill accessor»), and that implementations are not allowed to change this semantic for any function except non-strict plain functions. The actual behavior of the arguments property, if it’s anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill Function.prototype.arguments accessor to specially handle this values that are non-strict functions.

(function f()  if (Object.hasOwn(f, "arguments"))  console.log( "arguments is an own property with descriptor", Object.getOwnPropertyDescriptor(f, "arguments"), ); > else  console.log( "f doesn't have an own property named arguments. Trying to get f.[[Prototype]].arguments", ); console.log( Object.getOwnPropertyDescriptor( Object.getPrototypeOf(f), "arguments", ).get.call(f), ); > >)(); // In Chrome: // arguments is an own property with descriptor // In Firefox: // f doesn't have an own property named arguments. Trying to get f.[[Prototype]].arguments // Arguments 

Examples

Using the arguments property

function f(n)  g(n - 1); > function g(n)  console.log(`before: $g.arguments[0]>`); if (n > 0)  f(n); > console.log(`after: $g.arguments[0]>`); > f(2); console.log(`returned: $g.arguments>`); // Logs: // before: 1 // before: 0 // after: 0 // after: 1 // returned: null 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 12, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Читайте также:  Удаление элемента бинарного дерева java
Оцените статью