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

171
Views
Hoisting vs Scope Chain

How come, in the first block of code, I get "Hello", but in the second block of code, I get undefined, then "bye"?

For the first block of code, I get that it is going up the scope chain to get the hoisted variable "Hello", which I get the expected result.

    var greet = "Hello";

    var sayHi = () => {
        console.log(greet);
    }

    sayHi();

However, I'm struggling to understand how come, if I declare the variable greet after the first instance of console.log, I get undefined first? Shouldn't the JS engine go up the scope chain to find "Hello" first?

        var greet = "Hello";

    var sayHi = () => {
        console.log(greet);

        var greet = "Bye"; 
        console.log(greet);
    }

    sayHi();
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

There is a difference between declaration and initialization. Declaration creates the variable, initialization assigns it its initial value. The statement var greet = "Bye"; contains both things, but only the declaration is hoisted.

about 4 years ago · Juan Pablo Isaza Report

0

In the second block after hoisting, it is executed as below. That's why you see undefined and then Bye.

var greet = "Hello";

    var sayHi = () => {
        var greet;
        console.log(greet);

        greet = "Bye"; 
        console.log(greet);
    }

    sayHi();

Within the function, it sees the greet variable is defined in its scope. It won't look up in the scope chain as you expect.

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!