JavaScript Function ES6

ES6 offers some cool new functional features that make programming in JavaScript much more flexible. Let’s talk about some of them — specifically, default parameters, rest parameters, and arrow functions.

Default parameters in ES6

function counts(number1 = 5, number2 = 10) {
  // do anything here
}

number1 and number2 are assigned default values of ‘5’ and ‘10’ respectively.
Well yeah, this is pretty much it. Short and sweet. No extra code to check for a missing parameter. This makes the body of the function nice and short. 🙃

NOTE: When a value of undefined is passed for a parameter with default argument, as expected the value passed is invalid and the default parameter value is assigned. But if null is passed, it is considered valid and the default parameter is not used and null is assigned to that parameter.

A nice feature of default parameters is that the default parameter doesn’t necessarily have to be a primitive value, and we can also execute a function to retrieve the default parameter value. 

Example

function getDefaultParam() {
  return 10;
}

function multiply(first, second = getDefaultParam()) {
  return first * second;
}

console.log(multiply(5, 1));  // 5
console.log(multiply(10));    // 100

 

Previous parameters can also be default parameters for the parameters that come after them like so:

function multiply(first, second = first) {
  // do something here
}

But the inverse will throw an error. That is, if the second parameter is assigned as the default value for the first parameter, it results in an error because the second parameter is not yet defined while being assigned to the first parameter.

function add(first = second, second) {
  return first + second;
}
console.log(add(undefined, 1)); //throws an error

 

Rest Parameters

rest parameter is simply a named parameter which is preceded by three dots(…). This named parameter becomes an array which contains rest of the parameters(i.e apart from the named parameters) passed during the function call.

Just keep in mind that there can only be one rest parameter, and it has to be the last parameter. We can’t have a named parameter after a rest parameter.

Example

function pickProperties(object, ...properties) {
  let result = {};

  for (let i = 0, len = properties.length; i < len; i++) {
    result[properties[i]] = object[properties[i]];
  }
  return result;
}
let vehicle = {
  typeOfVehicle: 'car',
  name: 'VANTAGE',
  maker: 'Aston Martin',
  color: 'grey'
};
let vehicleData = pickProperties(vehicle, 'typeOfVehicle', 'maker', 'color');
console.log(vehicleData.typeOfVehicle); // "car"
console.log(vehicleData.maker); // "Aston Martin"

 

As you can see we’ve used the rest parameter to get all the keys/properties to be extracted from the passed object, which is the first parameter.

The difference between a rest parameter and the ‘arguments object’ is that the latter contains all the actual parameters passed during the function call, while the ‘rest parameter’ contains only the parameters that are not named parameters and are passed during the function call.

Arrow Functions

Arrow Functions, or “fat arrow functions,” introduce a new syntax for defining functions that is very concise. We can avoid typing keywords like functionreturn and even curly brackets { } and parentheses ().

Syntax

The syntax comes in different flavors, depending on our usage. All the variations have one thing in common, i.e they begin with the arguments, followed by the arrow (=>), followed by the function body.

The arguments and the body can take different forms. Here’s the most basic example:

let mirror = value => value;
// equivalent to:
let mirror = function(value) {
  return value;
};

The above example takes a single argument “value” (before the arrow) and simply returns that argument(=> value;). As you can see, there’s just the return value, so no need for return keyword or curly braces to wrap up the function body.

Since there is only one argument, there’s no need for parentheses “( )” as well.

Here’s an example with more than one argument to help you understand this:

let add = (no1, no2) => no1 + no2;
// equivalent to:
let add = function(no1, no2) {
  return no1 + no2;
};

If there are no arguments at all, you must include empty parentheses like below:

let getMessage = () => 'Hello World';
// equivalent to:
let getMessage = function() {
  return 'Hello World';
}

For a function body with just a return statement, curly braces are optional.
For a function body having more than just a return statement, you need to wrap the body in curly braces just like traditional functions.

Here’s a simple calculate function with two operations — add and subtract. Its body must be wrapped in curly braces:

let calculate = (no1, no2, operation) => {
    let result;
    switch (operation) {
        case 'add':
            result = no1 + no2;
            break;
        case 'subtract':
            result = no1 - no2;
            break;
    }
    return result;
};

 

Now, what if we want a function that simply returns an object? The compiler will get confused whether the curly braces are of the object (()=>{id: number}) or curly braces of the function body.

The solution is to wrap the object in parentheses. Here’s how:

let getTempItem = number => ({ id: number});
// effectively equivalent to:
let getTempItem = function(number) {
    return {
        id: number
    };
};