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

227
Vistas
A vaiable declared inside a function cant be accessed from a block that is in another function?

So 'rand' is declared inside a function called 'makeMysteryFunc', why when console.log(rand) will not print the numerical value that is randombly generated but in stead just print it as console.log(rand).

Anybody can explain the scope here?

hi question here
question about scoping
function makeMysteryFunc () {
    const rand = Math.random()
    console.log(rand);

    if (rand > 0.5) {
            return function () {
            console.log(rand);
            console.log(above 0.5)
    }

    } else {
            return function () {
            console.log(below 0.5)
    }
    }

}
why cant console.log(rand) be printed when it is declared inside a function ????

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

0

I don't understand the problem. Your example (after fixing syntax issues, see below), works properly for me.

function makeMysteryFunc () {
    const rand = Math.random();
    console.log(rand);

    if (rand > 0.5) {
        return function () {
            console.log(rand);
            console.log("above 0.5");
        }
    } else {
        return function () {
            console.log(rand);
            console.log("below 0.5");
        }
    }
}

const f = makeMysteryFunc();
f();

Prints, for example,

0.5095959852493863
0.5095959852493863
above 0.5
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