Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
let calculatorIsOn = false;

const pressPowerButton = () => {
if (calculatorIsOn) {
console.log('Calculator turning off.');
calculatorIsOn = false;
} else {
console.log('Calculator turning on.');
calculatorIsOn = true;
}
};

pressPowerButton();
// Output: Calculator turning on.

pressPowerButton();
// Output: Calculator turning off.

What I have tried:

I wanted to know that why they assign another value in 4th line calculatorIson =false; .. and also want to understand whole program..
please help me understand me this I am at very early stage of JavaScript..
Thanks in Advance..
Posted
Updated 5-Jan-18 0:43am

Actually it is TypeScript [^]
The equivalent code in Javascript is
var calculatorIsOn = false;
      function pressPowerButton() {
          if (calculatorIsOn) {
              console.log('Calculator turning off.');
              calculatorIsOn = false;
          }
          else {
              console.log('Calculator turning on.');
              calculatorIsOn = true;
          }
      };
      pressPowerButton();
      // Output: Calculator turning on.
      pressPowerButton();
      // Output: Calculator turning off.


go through these links you will get to know
let keyword in TypeScript [^]
const · TypeScript Deep Dive[^]
=> Typescript Arrow Functions[^]

refer inline comments for TS code
  let calculatorIsOn = false;  // global variable declaration

        const pressPowerButton = () => {  // defining a function , refer arrow functions
            if (calculatorIsOn) {          // check whether the variable is true 
console.log('Calculator turning off.');
        calculatorIsOn = false;                 // set the variable  as false 
        } else {
            console.log('Calculator turning on.');  // log the result in the console window 
            calculatorIsOn = true;          // set the variable as true 
        }
        };
        pressPowerButton(); // call the function 
 
Share this answer
 
v3
It is using calculatorIsOn as a global variable to define if the calculator is on or not and the power button acts as a toggle so if the calc is on when the power is pressed it has to be off, and when it is off it has to be on, so the code is simply toggling the value of calculatorIsOn. The code could be simplified to simply

calculatorIsOn = !calculatorIsOn;


That will make the value true if it is false and false if it is true.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900