CodeBlanks Logo Icon CodeBlanks

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.

Practice 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)).

Starter code

script.js
// Define the formatPrice function here
// It takes an amount parameter
// Create a result variable inside
// Return the result variable

// Print the result

Sample solution

script.js
function formatPrice(amount) {
  let result = amount + " USD";
  return result;
}

console.log(formatPrice(50));

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does this code print?

script.js
function calc(x) {
  return x * 2;
}
console.log(calc(5));
  • 5
  • 10 Correct answer
  • undefined
  • 2

Explanation: calc(5) = 5*2 = 10 is returned and printed.

2 Match each concept to its meaning

Term Meaning
return Returns a value
parameter Placeholder in declaration
argument Actual value in call
scope Where a variable lives

3 Complete the function declaration

Question
function cube(____) {
  return n * n * n;
}
console.log(cube(3));
Answer
function cube(n) {
  return n * n * n;
}
console.log(cube(3));

Explanation: cube(n) takes an n parameter.

All lessons in Beginner