Summary - Functions
Write a VAT calculation function and call it with different amounts.
Summary - Functions
In this group you learned the basics of functions. A function is a reusable block of code; you declare it with the function keyword and call it with (). It returns a value with return; without it, you get undefined.
A parameter is the placeholder in the declaration; an argument is the value in the call. You can assign a function to a variable to create a function expression. Variables inside a function only live in that function's scope.
Exercise Write a combined function
Define a function called formatPrice. It should take an amount parameter. Inside it, declare a local variable with let result and assign it a text. Then return result. Finally print the result with console.log(formatPrice(50)).
Show example solution
function formatPrice(amount) {
let result = amount + " USD";
return result;
}
console.log(formatPrice(50));
Test yourself
-
What does this code print?
function calc(x) { return x * 2; } console.log(calc(5));- 10
- 5
- undefined
- 2
Show answer
10 — Correct. calc(5) = 5*2 = 10 is returned and printed.
-
Match each concept to its meaning
- return
- Returns a value
- parameter
- Placeholder in declaration
- argument
- Actual value in call
- scope
- Where a variable lives
-
Complete the function declaration
function cube(____) { return n * n * n; } console.log(cube(3));Show answer
function cube(n) { return n * n * n; } console.log(cube(3));