Rest Your Love On JavaScript

Rest Your Love On JavaScript

We choose love for the rest of our lives while JavaScript chooses rest of the function parameters. Using the rest parameter one can express their loads of love and parameters to any function. In this article, we are falling again in love and JavaScript by understanding one more awesome feature; the rest parameter.

When you start loving the rest will follow along. In JavaScript too, when you want to supply too many parameters to a function you just leave it to the rest parameter. At very first glance rest looks may astonish you but it is super friendly. Such a super friendly feature was added with the JavaScript’s ES6 (ES 2015) release and has been in use without any guilt. When you want to provide an arbitrary number of parameters to a function where you are not aware of how much it will be; then you can simply use the rest parameter to take care of it. We will figure out how the rest parameter helps you to solve your daily household coding problem by checking out life without and with the rest parameter.

  • Life without Rest
  • Rest to the rescue

Now less talking more coding!

Life without Rest

JavaScript functions don’t give a func about extra parameters, they simply ignore them.

function add(num1, num2) {
return num1 + num2
}

console.log(add(100, 200, 500)) // 500 is ignored, lol

// 300

Here, the value 500 is simply ignored by the function without even raising any error; this would be an error in other programming languages like Java, C# etc.

Arguments Keyword

One way to remember the forgotten is to use arguments keyword within a function.

function add(num1, num2) {
return num1 + num2 + arguments[2]
}

console.log(add(100, 200, 500))

// 800

// [Arguments] { '0': 100, '1': 200, '2': 500 }

But the arguments keyword doesn’t jam with arrow functions.

const add = (num1, num2) => {
return num1 + num2 + arguments[2]
}

console.log(add(100, 200, 500))

// 300[object Object]

// arguments returns root level object
// (for browser it is window, for Node.js it is module wrapper variables)

Along with this, there are several other issues with the arguments keyword.

The fall of arguments keyword:

  • it is an object acting as an array
  • provide all parameters (given or not given)
  • doesn’t jam with arrow functions
  • not an array, so can’t use array functions
  • syntactically weirdo

Rest to the rescue

Put 3 dots before a function’s parameter and call it a rest parameter (…rest).

function add(...numbers) {
let total = 0
for (const num of numbers) {
total += num
}
return total
}

console.log(add(100, 200, 500))

// 800

Here, numbers is a rest parameter that allows the add function to accept an arbitrary number of values whenever it will be invoked; and we are simply summing up the supplied numbers by adding them all.

If you log the numbers parameter directly you will come to know it is nothing but an array.

function add(...numbers) {
console.log(numbers)
}

add(100, 200, 500)

// [ 100, 200, 500 ]

Well, well, well, if the rest parameter is simply an array; let us leverage the power of array functions.

const add = (...numbers) => numbers.reduce((acc, crr) => acc + crr, 0)

console.log(add(100, 200, 500))

// 800

Rest parameters can also jam with arrow functions as shown below:

const add = (...numbers) => numbers.reduce((acc, crr) => acc + crr, 0)

console.log(add(100, 200, 500))

// 800

Another tiny rule to use rest parameter is that it must be the last parameter in a function’s parameter list.

const info = (name, age, ...skills, gender) => `${name} ${age} - ${skills.join(', ')}`

console.log(info('John', 21, 'Python', 'Bootstrap', 'Sass'))

// Uncaught SyntaxError: Rest parameter must be last formal parameter

If failed to do so then it will lead to an error; an error nobody wants and devs aren’t nobody.

Rest can also be used when destructuring an object/array. It simply a way to getting what you need out of many other object properties or array values and leaving the rest of it accessed through rest object/array. Check out below code to understand previously written english statement:

const [hobby, ...otherHobbies] = ['Football', 'Swimming', 'Boxing']

console.log(hobby)
console.log(otherHobbies)

const { department, ...otherDetails } = {
id: 1,
name: 'John Doe',
salary: 1200,
department: 'Accounts'
}

console.log(department)
console.log(otherDetails)

// Football
// [ 'Swimming', 'Boxing' ]
// Accounts
// { id: 1, name: 'John Doe', salary: 1200 }

Summarizing the rise of rest parameter:

  • its simply an array
  • benefited with array functions
  • jam with arrow functions
  • must be the last parameter
  • can also be used when destructuring object/arrays
  • syntactically awesome

Git Repository

Check out the git repository for this project or download the code.

Download Code

Git Repository

Summary

Love is an expression so do the rest parameters in JavaScript. Understanding both is crucial for writing beautiful codes and life codes. It is a super awesome feature that you can try and use if the situation demands it. It is better to know for 2 additional reasons; first expanding your JavaScript wisdom another one is understanding your senior’s written code like a pro.

Hope this article helps.

Originally published at codeomelet.com.