by Sai gowtham

How to use the Rest Parameters (...) in JavaScript

In JavaScript, the rest parameters (…) help us to represent the infinite number of function arguments as an array.

function sum(a,b,...remaining){

     console.log(a);

     console.log(b);

     console.log(remaining)
}

console.log(sum(1,2,3,4,5,6,7))

//a -> 1

//b - > 2

//remaining - > [3,4,5,6,7]

In the above code sum function accepts three arguments a, b and remaining. where the first two arguments values are 1,2 everything we passed after the first two arguments are represented as an array.

function sortNumbers(...numbers){
    return numbers.sort((a,b)=>a-b)
}

console.log(sortNumbers(4,5,6,2,1,7,3))

//Output--> [1,2,3,4,5,6,7]

If we prefix any parameter with (…) that parameter can accept unlimited arguments and represent it as an array. Like in the above example we prefixed ...numbers so that it can accept many arguments.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course