JavaScriptLesson 5 of 16
Functions and arrow functions
A function is a named piece of code you can call as often as you like with different data. Describe once how a discount works, then use it for any price.
Key points
- function name(a, b) { … } declares it, name(1, 2) calls it
- return hands the result back; without it a function returns undefined
- A default parameter: function greet(name, greeting = "Hi")
- An arrow function: const square = (n) => n * n, shorter, with return implied
- Calls can be nested: in double(square(3)), square runs first, then double
Example
function greet(name, greeting = "Hi") { return `${greeting}, ${name}!`;} const square = (n) => n * n;const double = (n) => n * 2; console.log(greet("Ana"));console.log(greet("Leo", "Good morning"));console.log(square(4), double(square(3)));greet was called twice, and without a second argument the default kicked in. On the last line square(3) returned 9 and double turned it into 18.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.The shop is having a sale. Finish discount(price, percent) so it returns the price minus percent per cent, and rewrite formatPrice as an arrow function that returns the price with two decimals and USD. The program should print 60.00 USD, 17.99 USD and 5.00 USD.
Output
What your program prints appears here.