Default Parameters – ECMAScript 6

In JavaScript, parameters of functions default to undefined. However, in some situations, it might be useful to set a different default value.

In the past, the default value for a parameter is defined in the function body based on the value of the parameter as below:

function multiply(a, b) {
    b = (typeof b !== 'undefined') ? b : 1;
    return a * b;
}

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

In the above code snippet the typeof parameter b is being checked, if the value is undefined then the value is set to 1.
Sometimes people will be using || operator to set default value as below

function multiply(a, b) {
    a = a;
    b = b || 1;
    return a * b;
}

console.log(multiply(5, 5)); // 25 -- value of b is 5
console.log(multiply(5)); // 5 -- value of b is 1, which taken from
                      // initialization using || operator

This pattern is most used but is dangerous when we pass values like

console.log(multiply(5, 0));

Because the 0 is falsy, and so the b || 1 results in 1, not the directly passed in 0. To handle this, coders started initializing value in function bodies.

In ECMAScript 6, the checks in the function body are no longer needed, we can define the default value in function head itself as follows:

function multiply(a, b = 1) {
    return a * b;
}

console.log(multiply(5, 2)); // 10 -- value of b is 2
console.log(multiply(5, 5)); // 25 -- value of b is 5
console.log(multiply(5)); // 5 -- value of b is 1, which taken from
                  // default parameter initialization

console.log(multiply(5, undefined)); // 5 -- value of b is 1,
                 // even if we pass  undefined as value to parameter b

The default value for parameter b is initialized from function head if it didn’t have any valid input.

If we convert the above ES6 code into native javascript code using Babel transpiler, we will get the following equivalent code

"use strict";

function multiply(a) {
    var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;

    return a * b;
}

console.log(multiply(5, 2)); // 10 -- value of b is 2
console.log(multiply(5, 5)); // 25 -- value of b is 5
console.log(multiply(5)); // 5 -- value of b is 1, which taken from
// default parameter initialization

console.log(multiply(5, undefined)); // 5 -- value of b is 1,
// even if we pass  undefined as value to parameter b

ECMAScript 6 is a syntactic sugar for the existing components 🙂

Happy Coding 🙂

filter() – Javascript Functional Programming

Previously, we have explored map() in JavaScript. Now it’s time to see how to use the filter() in our JavaScript code.

The filter() is a function on the array that accepts another function as its argument which it will use to return new filtered version of the array.

Let’s take an array to experiment

var games = [
    { name: 'cricket', type: 'outdoor' },
    { name: 'football', type: 'outdoor' },
    { name: 'chess', type: 'indoor' },
    { name: 'carrom', type: 'indoor' }
];

It’s a pretty simple array, doesn’t it? We are going to use the same array in all the code throughout the post.

Now we are going to filter out the games from the array which are played in outdoor.

So, as always let me do this by using for loop.

var outdoorGames = [];
for (var i = 0; i < games.length; i++) {
    if (games[i].type == 'outdoor')
        outdoorGames.push(games[i])
}

console.log(outdoorGames);

Lets the write output in the console.

Output
[Object, Object]
    0: 
        Objectname: "cricket"
        type: "outdoor"
    1:
        Objectname: "football"
        type: "outdoor"

Yeah! We have achieved what we want in the output. We have extracted the outdoor game names from the game’s array.

Now, Let’s use the filter() in our code to get the similar output. Let’s rewrite the code.

We have the filter which accepts one argument which is a function. The filter will loop through each item in the array, so we don’t have to initialize index or iterate the loop as we did in the for loop.
And each item will be passed into callback function and it will return whether the condition ‘outdoor’ satisfies or not.

When we reduce the number of lines in the code, it doesn’t mean the code becomes faster unless it actually does.

var games = [
    { name: 'cricket', type: 'outdoor' },
    { name: 'football', type: 'outdoor' },
    { name: 'chess', type: 'indoor' },
    { name: 'carrom', type: 'indoor' }
];

function isOutdoor(game) {
    return game.type == 'outdoor';
}

var filteredOutdoor = games.filter(isOutdoor);

console.log(filteredOutdoor);
// output
[Object, Object]
    0: 
        Objectname: "cricket"
        type: "outdoor"
    1:
        Objectname: "football"
        type: "outdoor"

We get similar output when we use a filter().

Now in ES6, let’s simply more using arrow function

var filteredOutdoorArrow = games.filter(game => game.type == "outdoor");

console.log(filteredOutdoorArrow);

Now it’s up to us to decide which module we have to use in our code – the code using a pure function or using the loops.

Let’s explore more about functional programming in upcoming posts.

Happy coding!