Exercise 2/7, how is the variable changing outside the function?


#1

I don’t quite understand how the variable “calculatorOn” changes! At first it is defined as false, as you can see in the code below. Then the function “pressPowerButton” is called once and inside it the variable’s value changes to true. Then the function is called again, but somehow it works as if the value of the variable is true. My question is: if the variable “calculatorOn” is equal to false all the time OUTSIDE the function, how the same variable will be seen as true when we execute the function twice?? I mean, the value “given” by the executed function is the one that matters, the one took into account?

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.

#2

As you start the program, the calculator is off.

If the calculator is on, pushing the button turns it off.

Else (if the calculator is off), pushing the button turns it on.

So,

var calculatorOn = false; is a global variable. Its value can be re-assigned later on in the program.

Thus when the calculator is off, its variable needs to say that it is not on (so false).
Else, if the calculator is off (as it is the case as per our global variable), we need to assign true to the variable to turn it on.

Don’t know if that’s clear but… there’s the idea.


The variable doesn’t miraculously change by itself, you need to tell the program what to do, and thus assign the variable the right value.


#3

The first time you call the function you are changing the variable’s value to true, as you noticed. Since the variable itself exists outside the function, you are able to reference it, check it, and change it from either inside the function or outside of the function. Since you have changed it to true, it will stay true forever until you do something to change it again. The second time you’re running the function changes it back to false because of how the function works, but you could also just write something like:

calculatorOn = false;

After your first function call, and that will change it back to false again directly. If you put that line in between your two function calls the variably would be changed to true both times the function runs. You could also try putting one of these:

calculatorOn = true;

Before your first function call, and then that first function would switch the variable to false because it finds that it is already true.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.