What’s new with ES2015 functions?
- Default parameters provide flexibility to functions in order to avoid errors when unexpected parameters are passed.
- Named parameters make it easier to understand how a function should be called (typically an object that contains local variables). The cool part is you can set a default for named parameters too!
The problem default parameters solve
Say we had a countPizzas
function as shown :
function countPizzas(pizzaArray) {
let pizzaLength = pizzaArray.length;
console.log(pizzaLength);
}
and we ran countPizzas(["Grilled Chicken Pesto", "Margherrita", "Cheese"])
we’d get 3
returned back to us.
But…
what if I passed countPizzas()
? or countPizzas(undefined)
?
“TYPE ERROR” FO SHO
We want to be able to expect unexpected arguments in our functions.
The solution
ES2015 gives us the power to pass default parameters!
This is what our function would look like:
function countPizzas(pizzaArray = []) {
let pizzaLength = pizzaArray.length;
console.log(pizzaLength);
}
now if we passed countPizzas()
? or countPizzas(undefined)
, our console would return 0
instead of throwing crazy type errors.
COOLSAUCE HUH .
The problem named parameters solve
Say we upgraded our countPizzas
function as shown but with a commonToppings parameter to count the common toppings found on the pizzas too :
function countPizzas(pizzaArray, commonToppings = {}) {
let cheese = commonToppings.cheese;
let basil = commonToppings.basil;
let chicken = commonToppings.chicken;
let pizzaLength = pizzaArray.length;
console.log(pizzaLength);
}
Without opening up the countPizzas function, it is unclear what our function expects. AND we’ve added all these extra locally scoped variables (cheese, basil, chicken).
The solution
We use named parameters to create locally scoped variables right in the argument. Take a look:
function countPizzas(pizzaArray, {cheese, basil, chicken} = {}) {
let pizzaLength = pizzaArray.length;
console.log(pizzaLength);
console.log(cheese);
console.log(basil);
console.log(chicken);
//now we have locally scoped "cheese", "basil", and "chicken" variables that return true or false
}
YAYAY. Now just looking at the function signature, we know the function expects those specific toppings.