Click here to Skip to main content
14,601,122 members
Rate this:
Please Sign up or sign in to vote.
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
Rate this:
Please Sign up or sign in to vote.

Solution 1

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 
   
v3
Rate this:
Please Sign up or sign in to vote.

Solution 2

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.
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100