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.
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.