Exercise - Fun with parameters
In this exercise, you'll create functions that have required, optional, and default parameters.
Required parameters
Open the Playground and remove any existing code.
Enter the following arrow function, which accepts three required parameters.
let addThreeNumbers = (x: number, y: number, z: number): number => x + y + z;
Try calling the function by entering
addThreeNumbers(10, 20)
. TypeScript raises the error Expected 3 arguments but got 2. An argument for 'z' was not provided. When it runs, the function returnsNaN
because the third argument was passed asundefined
, making the calculation invalid.What happens when you enter
addThreeNumbers(10, 20, 30, 40)
? TypeScript raises the error Expected 3 arguments but got 4. When it runs, the fourth argument drops off and the function returns60
.
Optional parameters
In the function, try making the
y
parameter optional. What happens?let addThreeNumbers = (x: number, y?: number, z: number): number => x + y + z;
TypeScript raises an error because the position of the optional parameters matter. In the parameter list, optional parameters must follow all required parameters. Instead of the
y
parameter, try making thez
parameter optional. Also, for this function to return the correct value, you must also update it to address the possibility thatz
may now be passed asundefined
. You should now be able to call the function usingaddThreeNumbers(10, 20)
oraddThreeNumbers(10, 20, 30)
.let addThreeNumbers = (x: number, y: number, z?: number): number => { if((z === undefined)) { return x + y; } else { return x + y + z; } };
Default parameters
Enter the following arrow function, which accepts three required parameters.
let subtractThreeNumbers = (x: number, y: number, z: number): number => x - y - z;
Assign a default value of
100
to thez
parameter by replacingz: number
withz = 100
.let subtractThreeNumbers = (x: number, y: number, z = 100): number => x - y - z;
Try calling the function with two and three arguments to test the result.
subtractThreeNumbers(10, 20); // returns -110 because 'z' has been assigned the value 100 subtractThreeNumbers(10, 20, 15); // returns -25