Introduction to Functions

A function is a block of code designed to perform a task.

Functions are like recipes. They take data or variables, perform a set of tasks on them, and then return the result. The beauty of functions is that they allow us to write a chunk of code once, then we can reuse it over and over without writing the same code over and over.

Take a look at this code:

var calculatorOn = false; function pressPowerButton() { if (calculatorOn) { console.log('Calculator turning off.'); calculatorOn = false; } else { console.log('Calculator turning on.'); calculatorOn = true; } } pressPowerButton(); // Output: Calculator turning on. pressPowerButton(); // Output: Calculator turning off.

This code turns the calculator on if it is currently off, and turns it off if the calculator is currently on.

See if you can figure out how this code works. In the next exercise, we'll walk through it line by line.


Think you've got it? Click 'Next' to continue.

Report a Bug
If you see a bug or any other issue with this page, please report it here.