How does this code work?

var calculatorOn = false;

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

// Output: Calculator turning on.

// Output: Calculator turning off.
  1. On line 1, we have a variable named calculatorOn set to false. Our program starts with the calculator in the off position.
  2. On line 3, there's a function named pressPowerButton. Functions follow this syntax:

    • They begin with the JavaScript keyword function.

    • After function comes the name of the function. pressPowerButton is the name of the function. Notice there are no spaces in the name and each new word is capitalized. This is a convention in the JavaScript community called camelCase.

    • After the function's name, comes parentheses (). We'll learn about these in the next exercise.

    • Finally, the function has a block of code it executes between the curly braces {}.

  3. Inside the function is an if/else statement.

  4. On the last few lines, we make the function run by writing pressPowerButton(). This term for this is calling the function. We call it with pressPowerButton(), and it runs all the code in the block of the function.
  5. We executed the code in the block of the function twice without having to write it twice. Functions can make code reusable!
Community Forums
Get help and ask questions in the Codecademy Forums
Report a Bug
If you see a bug or any other issue with this page, please report it here.