ES6 For Beginners : Default Functions Parameters

Share on FacebookTweet about this on TwitterShare on Google+Share on RedditShare on StumbleUponDigg thisFlattr the authorPin on PinterestShare on TumblrShare on LinkedInPrint this pageBuffer this page

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.

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

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.

 

Conclusion

Default function parameters in JavaScript ES6 adds syntactic sugar that makes reading and writing function simple.

 

Got A Question?

Hit me up in the comments here or on the comments section on my YouTube Channel or on twitter @pointDeveloper

 

Consider Subscribing / Donating
Subscribe To Mailing List
Donate
If my site was helpful to you, then please consider donating via paypal:

Prantik Vaghela (pointdeveloper)

Hi my name is Prantik Vaghela. I have done my Bachelors and Masters in Computer Science and am a web developer and now a Tutor through my blog. :-)

%d bloggers like this: