Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda