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

267
Views
Hoisting of "var" in javascript

I have read the following

Hoisting of var

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that if we do this:

console.log (greeter);
var greeter = "say hello"

it is interpreted as this:

var greeter;
console.log(greeter); // greeter is undefined
greeter = "say hello"

So var variables are hoisted to the top of their scope and initialized with a value of undefined.

But what happens with this (undefined) They move at the top then why it is "undefined"?

if (true) {
  console.log(hi)
}
var hi = 1

If they are pushed up, they would also have to be "read" first, wouldn't they?

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

0

Javascript only hoists declarations. The initialization is not hoisted.. The assignment only happens after your if condition.

This is also why some JS developers prefer let over var. If you use let, you will get a very clear error saying the variable cannot be

if (true) {
  console.log(hi);
}
let hi = 1;
//Uncaught ReferenceError: Cannot access 'hi' before initialization
about 4 years ago · Juan Pablo Isaza Report

0

The declaration is hoisted, but the assignment isn't.

It's really the same as the second example in your quote. So it's the equivalent of:

var hi;
if (true) {
  console.log(hi)
}
hi = 1

So hi is still undefined at the log statement.

This article has some good discussion and examples: https://blog.logrocket.com/demystifying-function-and-variable-hoisting-in-javascript/

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!