Default parameter value

In ES6, you can define the default values of a function's parameters. This is quite a useful improvement because the equivalent implementation in ES5 is not only tedious but also decreases the readability of the code.

Let's see an example here:

const shoppingCart = [];
function addToCart(item, size = 1) {
shoppingCart.push({item: item, count: size});
}
addToCart('Apple'); // size is 1
addToCart('Orange', 2); // size is 2

In this example, we give the parameter size a default value, 1. And let's see how we can archive the same thing in ES5. Here is an equivalent of the addToCart function in ES5:

function addToCart(item, size) {
size = (typeof size !== 'undefined') ? size : 1;
shoppingCart.push({item: item, count: size});
}

As you can see, using the ES6 default parameter can improve the readability of the code and make the code easier to maintain.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.79.147