Horje
What is the Difference Between Arguments object and Rest parameters in JavaScript?

The arguments and Rest Parameters is crucial for the writing efficient and modern JavaScript code. The arguments object has been traditionally used in functions to the access the parameters passed to them. However, with the introduction of the ES6 Rest Parameters provide the more readable and flexible way to the handle function arguments.

These are the following topics that we are going to discuss:

What is argument Object?

The arguments object is an array-like object accessible inside functions that contain the values of the arguments passed to that function. It is not an array but it can be converted into the one.

Syntax:

function example() {
console.log(arguments);
}

Example: It demonstrates arguments contains all the arguments passed to the sum function.

JavaScript
function sum() {
    let total = 0;
    for (let i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
}
console.log(sum(1, 2, 3, 4));

Output
10

What are Rest Parameters?

The Rest Parameters introduced in ES6 allow to the represent an indefinite number of the arguments as an array. This provides a more convenient and cleaner syntax compared to the arguments object.

Syntax:

function example(...args) {
console.log(args);
}

Example: The code demonstrates a function `sum` using rest parameters to compute the sum of any number of arguments passed to it.

JavaScript
function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4));

Output
10

Difference Between Argument Object and Rest Parameters

characteristics

Argument Object

Rest Parameters

Syntax

Implicit object

Explicit … notation

Data Structure

Array-like object

Array

Availability

Available in all functions

Must be explicitly defined

ES Version

ES1

ES6

Access Method

arguments[index]

Array methods (e.g. reduce, map)

Arrow Functions

Not available

Available

Use in Spread Syntax

Not supported

Supported

Length Property

arguments.length

args.length

Readability

Less readable

More readable




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Difference Between label and break in JavaScript Difference Between label and break in JavaScript
How to Format Dates in JavaScript with One Line of Code? How to Format Dates in JavaScript with One Line of Code?
Explain the Concepts of Service Workers in PWAs Explain the Concepts of Service Workers in PWAs
Sorted Linked List to Balanced BST using JavaScript Sorted Linked List to Balanced BST using JavaScript
LRU Cache using JavaScript LRU Cache using JavaScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
19