DEV Community

Cover image for [freeCodeCamp] ES6 - Arrow Function, Rest Parameter, Spread Operator
Prashant Sharma
Prashant Sharma

Posted on • Originally published at gutsytechster.wordpress.com

[freeCodeCamp] ES6 - Arrow Function, Rest Parameter, Spread Operator

Heya fellows! Here comes another JavaScript post that covers some amazing ES6 features which are widely used in current JavaScript environment. This is in continuation of my JavaScript learning from freeCodeCamp.

This post is going to be a bookmark for you. So, just start reading.

Anonymous functions

In JavaScript, we don't always need to give a name to a function. A function without a name is called an anonymous function. These are often used when we don't need to reuse them.

One can write an anonymous function as

const myFunc = function() {
  const myVar = "value";
  return myVar;
}

Arrow functions

ES6 provides a cleaner and concise way to write an anonymous function with the help of arrow functions. The above function definition can also be written as

const myFunc = () => {
  const myVar = "value";
  return myVar;
}

Does it look the same? Focus on the => arrow and () before that.

This can further be written into a one-liner, when there is no function body and only a single return value. Arrow function syntax allows omitting the return statement and the brackets surrounding the code, in such cases.

Since the above function only declares a variable and return that variable. The above function can be re-written as

const myFunc = () => "value";

This will return the "value" by default. Isn't it awesome? :)

Arrow functions with parameters

We can also pass arguments to an arrow function, just like any other regular function. The parameters can be placed within the parentheses as

const adder = (num) => num++;

The above method takes an argument num, adds 1 to it and return the updated value. Don't forget, there is an implicit return already.

Tip:- If an arrow function requires a single argument, the parenthesis around the parameter can be removed.

The above can also be written as

const adder = num => num++;

That doesn't mean that you can't pass multiple arguments to an arrow function. You can pass as many arguments as you want.

const multiplier = (a, b) => a * b;

Default parameters

ES6 allows the function to be more flexible with the use of default parameters. The default parameters are used when no arguments are specified i.e. when the parameter's value is undefined.

It'll be easier to understand with an example

const greeting = (name = "Anonymous") => "Hello" + name;

console.log(greeting("Prashant")); // Hello Prashant;
console.log(greeting());  // Hello Anonymous;

You can see, that when I provided the argument "Prashant", the name parameter used that value. However, when I called the function without any argument, the default value is used.

Rest Parameters in function

We can provide the variable number of arguments to the function with the help of rest parameters. The arguments provided, are stored in an array which can be manipulated from inside of the function.

Consider this piece of code, from freeCodeCamp's lesson

function howMany(...args) {
  return "You have passed " + args.length + " arguments.";
}

console.log(howMany(0, 1, 2)); // You have passed 3 arguments.

console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments

Rest parameters are defined using the three dots followed by the array variable i.e. ...args is a rest parameter.

Spread Operator

ES6 provides us with the spread operator, which allows us to expand arrays in-place.

Let's understand the benefits of the spread operator and how to use them.

Quest - Finding Maximum of an array

Before anything, let me introduce the Math.max() function. By the looks of it, you can guess that it would return the maximum of the elements provided to the function.

Math.max(1, 2, 3, 4);  // returns 4 as it is the maximum

This works perfectly. However, this function takes comma-separated arguments, not an array. If we were to store elements in an array and then try to use this function

const arr = [1, 2, 3, 4];
Math.max(arr);  // returns NaN

Since this function doesn't recognize arr as a valid argument. The output makes sense.

In ES5, if we were to find the maximum of elements present in an array, we would need to use Math.max.apply() function as

Math.max.apply(null, arr); // returns 4

Now, we can get the maximum number present in an array without explicitly providing each array value as a separate argument to Math.max().

With the use of the spread operator, we can use the array and still don't need to use the apply(), which makes the code more readable and easier to maintain.

const arr = [1, 2, 3, 4];
Math.max(...arr);  // returns 4 now

What exactly happened here? ...arr expanded the arr array in-place i.e. it spreads the element of an array. This is exactly how we use the spread operator to expand an array. Therefore

Math.max(...arr) ≡ Math.max(1, 2, 3, 4)

You might wonder that it looks exactly like the Rest parameter. Yes, it does, syntax-wise. However, when you need to collect values into an array, you use rest parameter(collecting values passed via arguments) and when you need to spread values(reassigning values to an array), you use spread operator. You may see it as different names for different operations.

The values of an array are substituted in place with the help of the spread operator.

Another Example

Let's consider one more example of its use

const ar1 = [1, 2, 3, 4]
const arr2 = [5, 6, 7, 8]

If you would want to merge these two arrays into a single one, you can use the spread operator as

const arr3 = [...arr1, ...arr2];

Here, the values of arr1 and arr2 have been spread in-place. Now, even if you were to change the values of arr1 or arr2, the arr3 would always return the corresponding updated array. Isn't it another awesome feature? :)

Note:- You should know that spread operator works only in-place. For e.g. as an argument to a function or in an array literal. The following piece of code will not work

const spreaded = ...arr3;   // throws an error

Conclusion

This post covered some great ES6 features. The use of arrow function is very common nowadays and its use along with the rest parameter and spread operator makes it something really awesome.

References

I hope this post helped you to understand some other JS awesome features. Well, it's time to say Good Bye! Meet you in the next post. Till then be curious and keep learning.called

Top comments (0)