JavaScript Basics · Lesson 7 of 13

Functions

A function is a named block of code that you can run whenever you need it. You have been using one all along: console.log. Now you will write your own.

function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet("Noor");
greet("Luca");
  • function greet(name) { … } defines the function. Nothing runs yet.
  • name is a parameter: a variable that receives a value each time the function is used.
  • greet("Noor") calls the function. "Noor" is the argument that goes into name.

A function can have several parameters, separated by commas, or none at all.

Returning a value

Most functions calculate something and hand it back with return:

function area(width, height) {
  return width * height;
}

const room = area(4, 5);
console.log(room);          // 20
console.log(area(2, 3));    // 6

A call to the function is replaced by the value it returns, so you can store it, print it, or use it in a bigger calculation.

return also ends the function immediately. Lines after it do not run.

Printing and returning are different. console.log shows a value to a person. return gives a value back to the code that called the function. A function that only prints cannot be used in a calculation.

Why functions matter

Functions let you write a piece of logic once and use it everywhere. If it needs to change, you change it in one place. They also give a name to an idea, which makes programs easier to read.

Your Task

  1. Write a function double that takes one number and returns that number times 2.
  2. Write a function fullName that takes a first name and a last name and returns them joined with a space between.
  3. Print the result of double(21).
  • double is a function that returns twice its input
  • fullName returns both names with a space between
  • Both functions use return
  • 42 is printed by calling double(21)