Summary
In this lesson, you learned that:
- A function is a named piece of code that you write once and can run as many times as you need. Thanks to functions, you don't have to repeat code, and when you change a function, the change applies everywhere it's used.
- You define a function with the keyword
function, a name, parentheses with parameters and a body in curly braces:function printArea(width, height) { ... }. A definition alone doesn't run anything. - You call a function with its name and parentheses:
printArea(5, 6);. It's good practice to define functions first and call them below. - A parameter is a name in the definition, an argument is a value in the call. Arguments go into parameters in order. A parameter that gets no argument is
undefined, unless it has a default value:function printPrice(price, currency = "EUR"). returngives a value back to the place of the call, so you can use the call like a value:console.log(add(2, 3)),const total = add(2, 3) * 2;.console.logonly shows a value. A function withoutreturnreturnsundefined.returnends the function right away, and the rest of the function doesn't run. With conditions, the firstreturnthat runs wins.- Variables created inside a function, and its parameters, exist only inside that function: they are local. Variables from outside can be used inside functions. To get a value out of a function, return it.
- A function can take an array, go through it with a loop and return a result. The
returngoes after the loop. - Arrow functions are a shorter way to write functions:
const add = (a, b) => a + b;returns the value after the arrow. With a body in curly braces, you needreturn:const area = (width, height) => { ... return ...; };.
In the next lesson, Objects, you will learn to keep values that belong together, such as a person's name and age, in a single value.
Instructions
- 1
Let's practice. Write a function
cartTotalwith two parameters:prices(an array of prices) anddiscountwith the default value0. The function returns the sum of the prices minus the discount. PrintcartTotal(cart)andcartTotal(cart, 50). The program prints280and230. - 2
Write an arrow function
formatPricewith a parameterpricethat returns the price as text with the currency, for example230 EURfor230. Use it to print the discounted total:formatPrice(cartTotal(cart, 50)).