Skip to content

Instantly share code, notes, and snippets.

@pseudosavant
Last active October 1, 2023 21:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pseudosavant/8360384 to your computer and use it in GitHub Desktop.
Save pseudosavant/8360384 to your computer and use it in GitHub Desktop.
Explicitly declare global variables inside an immediately invoked function expression (IIFE).Benefits:1. It is very obvious when you are intending to export a variable from a function.2. You can create global variables and your static code analyzer (JSLint/JSHint) won't complain.
(function(global){
var x = 2,
y = Math.pow(x, 2);
global.z = y;
})(this);
console.log(x); // undefined
console.log(y); // undefined
console.log(z); // 4
@duhaime
Copy link

duhaime commented Jan 14, 2018

why not just window.z = y inside the IIFE?

@mahdisalmanzade
Copy link

i heard that every variable that you declare inside IIFE Function is just accessible inside that IIFE , so you cant access that variable from global scope so, how its possible to access a variable inside IIFE from OUTSIDE(Global Scope).

@mahdisalmanzade
Copy link

(function iffy(name){
var greeting = 'Hello';
global = 2;
console.log(greeting + ' ' + name);

}( 'John'));
console.log(global);

@mahdisalmanzade
Copy link

mahdisalmanzade commented Feb 2, 2020

when i log that global variable from global scope it return number of 2.
But i've read that every variable declared inside IIFE , cannot be accessed outside of that IIFE.
@duhaime
@pseudosavant

@duhaime
Copy link

duhaime commented Feb 2, 2020

@mahdisalmanzade if you paste the snippet above into your Chrome developer tools console, and comment out console.log(x) and console.log(y), you'll see that z does indeed get set in the global scope to 4.

Technically, though, there aren't any variables defined in the IIFE that are subsequently available in the global scope. This is because z is an attribute of global, which is already defined in the global scope (as is window in a web context).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment