1

Im currently studying to be a web developer, front and back end, and to help keep my code organized they suggest using IIFEs where necessary, if I were to use more than one IIFE could I call a function or variable from on IIFE in another IIFE? or is it only accessible within the IIFE its in? using Javascript by the way.

D LoCoder
  • 11
  • 2
  • 1
    Only if you nest the IIFEs. See https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – Teemu May 11 '22 at 04:28
  • You can still declare variables globally from within an IIFE. Obviously not recommended. – Robby Cornelissen May 11 '22 at 04:31
  • thank you, i did end up wrapping everything into one IIFE for simplicity and organization, however im having a different problem, i believe i have all my code in the correct order and my functions are correct, but my repo isnt working properly, cant get it to display even with browsers default stylings, could anyone help? my github is https://github.com/DLoCode/catch-em-all – D LoCoder May 12 '22 at 17:04

1 Answers1

2

It's only possible to access things across IIFEs if one of them deliberately exposes some of its parts globally. For example:

const myLibrary = (() => {
  // lots of code
  return {
    fn: () => console.log('running fn')
  };
})();

(() => {
  myLibrary.fn();
})();

or

(() => {
  // lots of code
  window.myLibrary = {
    fn: () => console.log('running fn')
  };
})();

(() => {
  myLibrary.fn();
})();

The usual way to solve this issue is to put your whole script into a single IIFE.

(() => {
  const myLibrary = {
    fn: () => console.log('running fn')
  };
  myLibrary.fn();
})();

For professional code, in anything other than toy snippets, I'd recommend using ES6 modules and a bundler like Webpack, which allows you to write code in separate files, import and export from other files as needed, and then puts everything together in a single ("bundled") script (composed of one huge IIFE) that you can put on your page.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320