Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda