- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM Node Lists
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
- JavaScript Useful Resources
- JavaScript - Questions And Answers
- JavaScript - Quick Guide
- JavaScript - Functions
- JavaScript - Resources
JavaScript - Rest Parameter
Rest Parameter
The rest parameter in JavaScript allows a function to accept a variable number of arguments as an array. When the number of arguments that need to pass to the function is not fixed, you can use the rest parameters.
The JavaScript rest parameters allow you to collect all the remaining arguments in a single array. The rest parameter is represented with three dots (...) followed by a parameter name. This parameter name is the array that contains all the remaining arguments.
Rest Parameter Syntax
The rest parameter in JavaScript involves using three dots (...) followed by a parameter name in the function declaration.
function functionName(para1, para2, ...theArgs){ // function body; }
Here para1, and para2 are ordinary parameters while theArgs is a rest parameter. The rest parameter collects the rest of arguments (here, arguments other than the corresponding to the parameters – para1 and para1) and assigns to an array named theArgs.
We can write the rest parameter in function expression also same as in the function declaration.
The rest parameter should always be the last parameter in the function definition.
function funcName(...para1, para2, para2){} // SyntaxError: Invalid or unexpected token
The function definition can have only one rest parameter.
function funcName(para1, ...para2, ...para3){} //SyntaxError: Rest parameter must be last formal parameter
Example: Variable Length Parameter List
The rest parameters are very useful when you want to define a function that can handle a variable number of arguments. Let’s take the following example −
<html> <body> <div> Rest parameter allows function to accept nay number of arguments.</div> <div id = "demo"> </div> <script> function sum(...nums) { let totalSum = 0; for (let num of nums) { totalSum += num; } return totalSum; } document.getElementById("demo").innerHTML = sum(10, 20, 30, 40) + "<br>" + sum(10, 20) + "<br>" + sum(); </script> </body> </html>
Output
Rest parameter allows function to accept nay number of arguments. 100 30 0
Here, the rest parameter nums allows the function to accept any number of number arguments.
Example: Finding the Maximum Number
JavaScript rest parameter simplifies the process of finding the max number among a set of given numbers.
In this example, we use rest parameter to numbers to collect all arguments passed to the function. The spread operator is used to pass the individual values to the Math.max() function.
<html> <body> <div> Finding the maximum number</div> <div id = "demo"> </div> <script> function getMax(...args){ return Math.max(...args); } document.getElementById("demo").innerHTML = getMax(10,20,30,40) + "<br>" + getMax(10,20,30); </script> </body> </html>
Output
Finding the maximum number 40 30
Here the rest parameter args allows the function getMax to accept any number of arguments.
Spread Operator and Rest Parameters
The spread operator (...) is closely related to rest parameters and is often used in conjunction with them. While the rest parameter collects function arguments into an array, the spread operator performs the opposite operation, spreading the elements of an array into individual arguments.
In the above example of finding the maximum number, we used both rest parameter and spread operator.
function getMax(...args){ // here ...args as rest parameter return Math.max(...args); // here ... works as spread operator }
Example
In this example, the spread operator ... is used to pass the elements of the numbers array as individual arguments to the multiply function.
<html> <body> <div> Spread operator in JavaScript<div> <div id="demo"></div> <script> function multiply(a, b, c) { return a * b * c; } const numbers = [2, 3, 4]; document.getElementById("demo").innerHTML = multiply(...numbers); </script> </body> </html>
Output
Spread operator in JavaScript 24
Rest Parameter vs. Arguments Object
The introduction of rest parameters has implications for how we handle variable-length parameter lists compared to using the arguments object. Let's compare the two approaches:
Rest Parameters
<html> <body> <div> Sum using rest parameter in JavaScript:</div> <div id = "demo"> </div> <script> function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } document.getElementById("demo").innerHTML = sum(1, 2, 3, 4, 5); </script> </body> </html>
Output
Sum using rest parameter in JavaScript: 15
Arguments Object
<html> <body> <div> Sum using arguments object in JavaScript:</div> <div id = "demo"> </div> <script> function sum() { const argsArray = Array.from(arguments); return argsArray.reduce((total, num) => total + num, 0); } document.getElementById("demo").innerHTML = sum(1, 2, 3, 4, 5); </script> </body> </html>
Output
Sum using arguments object in JavaScript: 15
While both approaches achieve the same result, the rest parameter syntax is more concise and readable. It also behaves more consistently with other modern JavaScript features.
Destructuring with Rest Parameter
The destructuring assignment is introduced in ES6. It allows us to access the individual values of the array without using array indexing. We can use the destructuring assignment to extract the values from the array created by rest parameter.
Example
In the example below, the destructuring assignment extracts the first two elements from the numbers array.
<html> <body> <div> Destructuring assignment with rest parameter</div> <div id = "demo"> </div> <script> function getFirstTwo(...numbers) { const [first, second] = numbers; return `First: ${first}, Second: ${second}`; } document.getElementById("demo").innerHTML = getFirstTwo(1, 2, 3, 4, 5); </script> </body> </html>
Output
Destructuring assignment with rest parameter First: 1, Second: 2