How to Use Self-Invoking Functions to Make Variables Global in JavaScript?

Estimated read time 1 min read

A self-invoking function (also known as an immediately invoked function expression, or IIFE) is a function that is invoked immediately after it’s defined. In JavaScript, you can use self-invoking functions to create a scope that is separate from the global scope, and to make variables global by assigning them to the global window object.

Here’s an example of how you can use a self-invoking function to make a variable global:

(function () {
  var x = 10;
  window.y = 20;

console.log(x); // ReferenceError: x is not defined
console.log(y); // 20

In the example above, the variable x is declared inside the self-invoking function, so it is not accessible outside of that function. However, by assigning y to the window object, you make it a global variable that can be accessed from anywhere in your code.

It’s important to note that making variables global can have unintended consequences, such as clashing with other variables that have the same name, or making it difficult to track the origin of the variable. So, it’s generally recommended to use global variables only when necessary and to minimize their use.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply