In this video I'll demonstrate how to set default values for function parameters.
Some programming languages let you define a function with default parameter values like this:
public void AddToCart(string productName, decimal price, int quantity = 1, string currency = "USD") {
// logic here
}
In fact, with ES2015 we can now do very much the same thing.
A nice feature in other languages that is not available in JavaScript is calling a function with named parameters.
Named parameters let us quickly override default parameter values.
To call this function and override the currency value but accept the default values for all other parameters preceding it would look something like this:
AddToCart("Bicycle", 100.00, currency: "CAD");
I call AddToCart with a product name and a price. Then I supply the function a currency parameter with the value of 'CAD' for Canadian Dollars.
The value of the quantity parameter will be 1 as that is the default value in the function's signature.
In JavaScript, specifically ES2015, we now have access to default parameters. In addition, we also have destructuring which provides a way to extract the values we need.
What I'm going to show you won't work in ES5 so you'll need a transpiler like Babel or TypeScript.
I'll be using TypeScript here but you can find the ES2015 solution in the notes below.