Lesson 6 of 14 · 8 min

Functions

A function is a named recipe. You write it once and use it as often as you like:

function double(n) {
  return n * 2;
}

console.log(double(4));   // 8
console.log(double(10));  // 20
  • n is a parameter: a placeholder for the value you pass in.
  • return sends a result back to whoever called the function, and stops the function.
  • double(4) calls the function with 4 as n.

Functions can take several parameters, separated by commas:

function fullName(first, last) {
  return `${first} ${last}`;
}

return is not the same as console.log

console.log only shows a value. return gives it back so the rest of the program can use it: store it, compare it, pass it on. The checks for this lesson call your functions and look at what they return.

Your task

Write three functions:

  1. greet(name) returns Hello, <name>!, for example greet("Tariro") gives "Hello, Tariro!".
  2. area(width, height) returns the area of a rectangle.
  3. isEven(n) returns true if n is even, otherwise false.
main.js
function greet(name) {
  // return a greeting
}

function area(width, height) {
  // return the area
}

function isEven(n) {
  // return true or false
}

console.log(greet("Tariro"));
console.log(area(4, 5));
console.log(isEven(7));

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…