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

161
Views
Why is let variable accessible within IIFE & var is not?

This IIFE code is able to access count

let count = 0;
(function immediate() {
  if (count === 0) {
    let count = 1;
    console.log(count);
  }
  console.log(count);
})();

But why is count undefined in this case?

var count = 0;
(function immediate() {
  if (count === 0) {
    var count = 1;
    console.log(count);
  }
  console.log(count);
})();
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you use var the variable declaration is hoisted, that mean that your code will be rewritted in the following way:

var count = 0;
(function immediate() {
  var count; // decalration of variable hoisted on the function scope
             // and the count variable now is undefined.
  if (count === 0) {
    count = 1;
    console.log(count);
  }
  console.log(count); // just this is printed.
})();

As you can se, the variable inside the if block is now overriding the global count.

The fact that this behaviour is not so obvius is the reason why many suggest to avoid using var as we can use let and const instead, that have a block scope.

Update

Thanks to the comment of @t.niese I think is wort to mention another difference between var vs let and const.

Like var, let and const are hoisted, but with this differencese:

  1. they have a block scope and not a function scope like var has
  2. they are declared but not initialized to undefined like var
  3. any attempt to access a variable declared with let and const before it is initialized will result in a ReferenceError exception, while accessing an undeclared variable or a hoisted var will return just undefined.
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!