0

I've got the following code block:

(function(){
  a = 1; 
  alert(a);
})();

When I open the console in Chrome, I can see the variable a, with a value of 1. Shouldn't it be invisible since it's in an IIFE?

enter image description here

FloatingRock
  • 6,741
  • 6
  • 42
  • 75

2 Answers2

3

a = 1 means that a is a global varialbe, it is not private. Write

var a = 1;

to make it private.

When you omit var, you can easily create global variables - very dangerous.

Some materials are here: Difference between variable declaration syntaxes in Javascript (including global variables)?

Community
  • 1
  • 1
Beri
  • 11,470
  • 4
  • 35
  • 57
2

Your code is falling prey to The Horror of Implicit Globals: You never declare a, and so the statement a = 1; creates a global variable, not a local one. (In loose mode. Thankfully, nowadays we have strict mode, in which that extremely strange behavior was changed to be the error it always should have been.)

If you add a var in front of a:

var a = 1;

...it'll be private, and you won't have access to it within the console except when paused on a breakpoint within that function. When you're paused on a breakpoint within the function, everything in scope within the function is in scope to the console (to make the console more useful).

It's really easy to accidentally create global variables in loose mode:

function foo() {
    var niftySpiffyThing;

    // ...

    niftySpiffything = 42;

    // ...
}

Call foo once and bam, you have a global called niftySpiffything (because of the lowercase t in thing).

This is one of many reasons to habitually use strict mode, by putting "use strict" at the top of the script or as the first expression within a function:

"use strict"; // Applies to all code in this script
(function(){
  a = 1; 
  alert(a);
})();

or

(function(){
  "use strict"; // Applies only to code within this function
  a = 1; 
  alert(a);
})();

Then you get an error instead of a global.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875