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

126
Views
Keeping the last value

what do I have to change to this code, so that it doesn't take "balls" with the value of 10 every time? More precisely, "balls" to keep their last value. Thank you in advance!

let balls = 10;
let randomB = Math.floor(Math.random() * 10) + 1;
if (randomB % 2 == 0) {
  balls++;
} else {
  balls -= 2;
}
console.log(balls)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

  1. For the requirement to repeat a code, you should wrap it in a function.

Documentation says:

Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is... a set of statements that performs a task or calculates a value...

  1. For the requirement to use a value in a function from the last run of the function, you should use a variable that relies in a scope external relational to the function.

Documentation says:

The current context of execution... The context in which values and expressions are "visible" or can be referenced... Scopes can also be layered in a hierarchy...

class Game {
  constructor(balls) {
    this.balls = balls;
  }
  step() {
    let randomB = Math.floor(Math.random() * 10) + 1;
    if (randomB % 2 == 0) {
      this.balls++;
    } else {
      this.balls -= 2;
    }
    return this.balls;
  }
}
const game = new Game(10);
do {
  stepResult = game.step();
  console.log(stepResult);
} while (stepResult != 0);

So:

  1. The function we made is actually a method, named step.
  2. The scope external related to the function (method) is it's class.
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!