Skip to content
the poor coder

How to return arguments in an array in javascript

Poor Man
Published
Reading time
1 min read
On this page

How to Return Arguments in an Array in JavaScript#

Returning multiple values from a function in Javascript is not a straightforward task. However, we can return arguments in an array format. Here are a few ways to accomplish this task:

Using the arguments Object#

The easiest way to return arguments in an array format is by using the 'arguments' object. This object is an array-like object that contains all the arguments passed to a function. Here's an example:

Text

function returnArgsArray() {
  return Array.from(arguments);
}

console.log(returnArgsArray(1, "two", true)); // [1, "two", true]

In the above code snippet, we are using the 'Array.from()' method to convert the 'arguments' object to an array.

Using Rest Parameters#

Another way to return arguments in an array format is by using rest parameters. Rest parameters are a new feature in ES6 that allow us to represent an indefinite number of arguments as an array.

Text

function returnArgsArray(...args) {
  return args;
}

console.log(returnArgsArray(1, "two", true)); // [1, "two", true]

In the above code snippet, we are using rest parameters to collect all the arguments passed to the function and return them as an array.

Using the Spread Operator#

The spread operator is another way to convert arguments to an array. The spread operator allows us to spread the elements of an array into individual arguments. Here's an example:

Text

function returnArgsArray() {
  const args = [...arguments];
  return args;
}

console.log(returnArgsArray(1, "two", true)); // [1, "two", true]

In the above code snippet, we are using the spread operator to convert the 'arguments' object to an array.

Conclusion#

These are some of the ways to return arguments in an array format in Javascript. Each method has its own advantages and disadvantages. However, using rest parameters is the most recommended way because it is a new feature in ES6 and provides a cleaner syntax.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC