JavaScriptLesson 6 of 10Jump to practice

Functions

Package code you want to reuse into functions with parameters and return values.

A function is a named block of code you can run whenever you need it. Write it once, use it many times.

Declaring and calling

Your first function
Open in editor
<script>
function greet(name) {
  console.log("Hello, " + name + "!");
}

greet("Emma");
greet("Diego");
greet("Sofia");
</script>
Result
  • function greet(name) declares the function. name is a parameter: a placeholder for a value.
  • greet("Emma") calls it. "Emma" is the argument that fills the placeholder.

Returning a value

return sends a result back to the code that called the function. The function stops there.

Price with sales tax
Open in editor
<script>
function withTax(price) {
  return price + price * 0.08;
}

const total = withTax(1000);
console.log("$1000 plus 8% sales tax:", total);
console.log("Two items:", withTax(200) + withTax(300));
</script>
Result

Because withTax() returns a number, you can store it, add it up or pass it to another function.

Default values

Give a parameter a default, used when no argument is passed:

function greet(name = "friend") {
  console.log("Hello, " + name);
}

greet();        // Hello, friend
greet("Emma");  // Hello, Emma

Arrow functions

A shorter way to write small functions. You’ll see them everywhere in modern code.

Arrow functions
Open in editor
<script>
// These two do the same thing
function squareA(n) {
  return n * n;
}
const squareB = (n) => n * n;

console.log(squareA(4), squareB(4));

// With more than one line, use braces and return
const describe = (name, age) => {
  const label = age >= 18 ? "an adult" : "a child";
  return name + " is " + label;
};
console.log(describe("Emma", 21));
</script>
Result

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Declare a function called greet.

     greet(name) {
      console.log("Hello, " + name);
    }

  2. Exercise 2

    Send the result back to whoever called the function.

    function double(n) {
       n * 2;
    }

  3. Exercise 3

    Complete the arrow function.

    const square = (n)  n * n;

Quiz: 3 questions

1. When does the code inside a function run?
2. What does a function give back if it has no return?
3. In function add(a, b), what are a and b?

Finish the practice to complete this lesson.