Skip to the content

Closures

JavaScript · Unit 10: More on functions

A function can be written inside another one. The inner one sees the outer one's variables, just like a block sees what's outside its braces.

function bill(price, n) {
  const total = () => price * n;
  return `You pay ${total()}`;
}
console.log(bill(30, 3));

Prints

You pay 90

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    Fill in the blank so sale takes 10% off a price and it prints 180.

  4. 4. Predict the output

    There are two counters. What does it print?

  5. 5. Find the bug

    This program should count three visits and print 3. Which line has the error?

  6. 6. Multiple choice

    What does this code do?

  7. 7. Put the lines in order

    Put the piggy bank in order to save 50, then 20, and print the total, 70.

  8. 8. Complete the code

    Fill in the blanks so the scoreboard counts two goals and prints 2.

  9. 9. Predict the output

    Someone tries to set the account to 0 from outside. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →