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

89
Views
var hoisting and scope availability

As we know var declarations get hoisted but with undefined value:

console.log(a); // undefined

var a = 2

But this code is different:

function foo() {
    console.log(a); 
}

function bar() {
    var a = 3;
    foo();
}

var a = 2;

bar(); // 2

Wy does it log 2 instead of undefined ?

Why var a's value became magically accessible before it's declaration ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're calling bar() after you initialize the variable, so it's not undefined any more.

See this simpler example:

function foo() {
    console.log(a); 
}

foo(); // a is not yet initialized, prints undefined

var a = 2;

foo(); // a is now initialized, prints 2

Hoisting just makes the variable declaration available (so you don't get an "Undefined variable" error). The initialization is just an assignment that happens in the normal order.

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!