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

231
Vistas
How do I make changes to a local variable without changing the global variable in javascript?
var i = 100;

function gamePlay() {
       
    while(i >= 0) {
        if (i>0) {
            console.log(i);}
        else{console.log(**i+1**);}
        i--;
    }
}
    

When I increse i by 1 (the part of the code that is bold), I'd like to make that change occur locally. The rest of the code should use global i but the problem is that the change applies globally and the rest of the code stops working when I add 1 to i. This is the case even if I substract 1 before closing the while loop.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Try this:

var i = 100;

function gamePlay() {
    let i2 = i; // local variable

    while(i2 >= 0) {
        if (i2 > 0) {
            console.log(i2);
        }
        else {
            console.log(i2+1);
        }

        i2--;
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

When you declare variables in a function, they are local to that specific function. But when you declare them outside of the function, they are global and can be used anywhere.

In your case var i = 100 is global and can be used in any function. So you need to declare another variable inside the while block.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Just use the name of that variable.

In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitly by typing the var keyword before the name of the variable.

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