On the problem that IIFE can keep variables private and pollute global variables

when learning JS"s IIFE, I saw a lot of tutorials saying that IIFE can keep variables private. For example,

(function foo() {
  var b = 7;
})();
console.log(b); // referenceError

the variable b cannot be accessed outside the function. But can"t the same effect be achieved by declaring it with a normal function here?

also see that there are tutorials that say that IIFE can prevent pollute global variables. For example,

var b = 5;

(function foo() {
  var b = 7;
})();

console.log(b); // 5

but can"t normal function declarations achieve the same effect?

I don"t understand what advantages IIFE has over normal function declarations in these two aspects

Mar.11,2021

in the landlord's code, IIFE avoids contaminating the global variable foo.
while direct declaration creates a global variable for foo.

other answers to questions about private variables are already excellent, so I won't repeat them.


when learning JS's IIFE, I saw a lot of tutorials saying that IIFE can keep variables private.

what we want to compare here is

var a = 1;
//
(function foo() {
  var a = 1;
})();

instead of comparing the difference between immediately executing function expression and function declaration or function expression executing , he is not a high-order function, the function scope is all the same, he just immediately executes .


after the ordinary function is declared, you have to call it yourself. In addition, the function itself is also a variable equivalent to the global space. Finally, for ordinary functions, you can get the variables in the function


through closures.

I've seen this question on Stack Overflow before:
there are three benefits of using IIFE:

  1. avoids using namespaces globally. Because IIFE can be run directly with anonymous functions. You can remove the foo and run it directly.
  2. uses IIFE to run itself, and you don't need to call it again. In English, it means self-documenting .
  3. A normal named function is not run immediately, and you may miscall it somewhere.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b38bfc-2c141.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b38bfc-2c141.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?