ES6 For Beginners : Default Functions Parameters

With ES6 we can now set default function parameters. Other programing languages like php already had a way to add default function parameters. This was not possible with previous versions of JavaScript but we got around it with conditional statements.

Before we look at how to add default parameter in JavaScript ES6, let’s first take a look at what we did until now,

Consider the following snippet of code.

1

2

3

4

5

6

7

functionsum(a,b)

{

a=typeofa!=='undefined'?a:42;

b=typeofb!=='undefined'?b:8;

console.log(a+b);

}

sum();

In the above code we have a function called sum which takes two arguments a and b. Note that we are calling sum() on line 7 without passing any arguments. On line 3 and 4 checking if the type of the variables is undefined or not using the ternary operator. I am using the ternary operator but this can be done in various other ways.

If we find that the values of the variables is undefined then we are setting default values 42 and 8 for a and b respectively.

As you can see this adds a few extra lines and can make the code difficult to read.

Now let’s see how we can add default parameter in JavaScript ES6, we will convert the above snippet of code as follows

1

2

3

4

5

functionsum(a=42,b=8)

{

console.log(a+b);

}

sum();

With ES6 we can set the default parameters right at the top inside the parenthesis along with our variables. This is not only easy to read but it make out code a few lines shorter which is always nice.