6 Must Known New Features in ES6 – Part 4: Default Parameters

UI5

These are the newest and most crucial features in ES6 or also known as ECMAScript 6, ES2015, or JavaScript 6. This series of articles explains them super simple for you. Plus, each article states how to use the specific feature at its best.

This is article 4 of the series. ES6 supports default parameters out of the box. This is rather a tiny but nevertheless useful feature. It makes the code clearer and closes a bit more the gap between most other modern languages.

How to Use the Default Parameter

For example, there is a function to add 1 to a given number:

function fnPlus1(iNumber) {
    
    return iNumber++;

}

let iNumber = 2;
iNumber = fnPlus1(iNumber);
console.log(iNumber); // 3

Now the function should work as well if no parameter is provided. If no number as a parameter is provided the function is supposed to use 0 as value for iNumber and therefore to return a 1. This means 0 is the default value for iNumber or iNumber is a default parameter with the value 0.

Before ES6 a default parameter would have looked like this:

function fnPlus1(iNumber) {
    
    iNumber = iNumber || 0; // set the default parameter

    return iNumber++;

}

let iNumber = 2;
iNumber = fnPlus1(iNumber);
console.log(iNumber); // 3

iNumber = fnPlus1();
console.log(iNumber); // 1

But now with ES6 it is possible to set the default parameter right in the round brackets of the function:

function fnPlus1(iNumber = 0) {

    return iNumber++;

}

let iNumber = 2;
iNumber = fnPlus1(iNumber);
console.log(iNumber); // 3

iNumber = fnPlus1();
console.log(iNumber); // 1

Functions as Default Parameters

But it is not only possible to assign primitive values to default parameters. For example, one can also assign a function. For instance, if the value for parameter needs first to be calculated or if there is a getter for the value:

function fnGetDefaultValue() {

    return 0;

}

function fnPlus1(iNumber = fnGetDefaultValue()) {

    return iNumber++;

}

let iNumber = 2;
iNumber = fnPlus1(iNumber);
console.log(iNumber); // 3

iNumber = fnPlus1();
console.log(iNumber); // 1
No Comments

FREE SAP Modules Overview! (Complete)

Plus, receive all future infographics and SAP tips & insights that are only shared with the private newsletter subscribers. 

Latest Poll
Essential Ressources

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu