Last active
October 1, 2023 21:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 |
@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
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