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

150
Vistas
Update global variables in two functions JavaScript

Though I am aware of "Global scope, function scope, block scope" in JavaScript. I got stuck in this code block.

I simplified the logics of the code as follows. What I expected is, the console.log(a, b, c) in execute function would be a = 3, b = 6, c = 9. But what I actually got is a = 0, b = 0, c = 0. What's going wrong and how to fix this? Thanks

(function() {
    let a,b,c;
    let conditions = [-1, 1, 2, 3 ];

    const execute = () => {
        for (let i=0; i<conditions.length; i++) {
            if (conditions[i] < 0) {
                a = 0;
                b = 0;
                c = 0;
            } else if (conditions[i] > 0) {
                update(a, b, c);
            }
        }
        console.log(a,b,c);
    }

    const update = (a, b, c) => {
        a = a + 1;
        b = b + 2;
        c = c + 3;
    }

    execute();

})()
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here, by not declaring params to update(), the assignments are made to the variables in the parent scope.

(function() {
    let a,b,c;
    let conditions = [-1, 1, 2, 3 ];

    const execute = () => {
        for (let i=0; i<conditions.length; i++) {
            if (conditions[i] < 0) {
                a = 0;
                b = 0;
                c = 0;
            } else if (conditions[i] > 0) {
                update(); // edit
            }
        }
        console.log(a,b,c);
    }

    const update = () => {
        a = a + 1;
        b = b + 2;
        c = c + 3;
    }
    execute();
})()

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