Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
Subtract method in object if greater than zero

I'm using a game object that has different getters and methods within it. One of the parameters of my assignment is that the "playerDies" method has to subtract 1 from the lives if it is greater than zero and it cannot go below 0 (so it can't be -1 which is what is happening now). This topic is fairly new to me so I'm not sure what I can do to execute the subtraction only when there is a specific value. I've tried using an if-else statement but that resulted in the code not working. My code:

var game = {
    lives: 3,
    coins: 0,

    get points() {
        return this.coins * 10;
    },

    playerDies: function() {
            return this.lives -= 1;
    },

    newGame: function() {
         this.lives = 3;
         this.coins = 0;
    },
};


console.log("lives = " + game.lives);    // should be 3
console.log("coins = " + game.coins);    // should be 0
console.log("points = " + game.points);  // should be 0
game.coins = 0;
console.log("points = " + game.points);  // should be 20
game.playerDies();
console.log("lives = " + game.lives);    // should be 2
game.playerDies();
game.playerDies();
game.playerDies();
console.log("lives = " + game.lives);    // should be 0
game.newGame();
console.log("lives = " + game.lives);    // should be 3
console.log("coins = " + game.coins);    // should be 0
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can put if statement in your playerDies method

playerDies: function() {
  if (this.lives > 0) {
    return this.lives -= 1
  }

  return 0
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!