Search⌘ K

Solution Review: Place Order

Understand how to effectively manage function arguments in JavaScript by using rest parameters, default values, and the spread operator. Explore practical solutions for setting defaults, handling optional parameters, and avoiding common pitfalls in argument passing.

Task 1

Let’s discuss the solution to the challenge presented in the previous lesson.

Solution

Solution
Exercise
const placeOrder = function(id, amount, shipping = (amount < 20 ? 5 : 10),
date = new Date()) {
console.log(' shipping charge for id: ' +
id + ' is $' + shipping + ' Date:' + date.getDate());
};
//shipping, if not given, is $5 if amount less than 20 else $10
//date is today's date unless given
placeOrder(1,12.10, 3, new Date('05/15/2018'));
placeOrder(1,25.20, 10);
placeOrder(1,12.05);
placeOrder(1,25.30);
placeOrder(1,25.20);

Explanation

  • In line 1, the ternary operator is used to check the condition if the amount is less than 20 or not. Here, the default value of shipping depends on the ...