Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!