Does it make sense an IIFE here?

const myArray = ["element_one", "element_two", "element_three"]
const randomIndex = (arrayLength) => Math.floor(Math.random() * Math.floor(arrayLength))

const randomPop = (() => {
  const indexArray = myArray.map((element, i) => i)
  return function () {
    return indexArray.splice(randomIndex(indexArray.length), 1)
  }
})()

console.log(randomPop())
console.log(randomPop())
console.log(randomPop())
console.log(randomPop())

The idea was to create a function randomPop() that pops random index elements from an array.
The snippet works as intended but…

I struggle with the idea of IIFE and for example that snippet can not accept arguments, I have to hardwire myArray on the second line, I dont know why and how to do it.

If I do…

const randomPop = ((anyArray) => {
  const indexArray = anyArray.map((element, i) => i
...
...
console.log(randomPop(myArray))

I would get an error: i cant map undefined

Also… once that indexArray is empty… I would like to remap it , im not sure how to.
I was playing clever using closures now I am a bit stuck :yum:

I would appreciate some help. I have not done proper javascript for months and I am struggling a little bit. Now time for a walk!!!

So to answer one of your inner questions (the snippet inside the IIFE can’t accept arguments), there is a workaround: give it arguments. :wink:

Here’s an IIFE with arguments:

const sayHello = (function(from, to){
  return `${from} says hello to ${to}!`;
})("Snowmonkey", "Josepagan"); 
// the trailing parentheses are passing parameters to the inner function, so in this case,
//   the `from` and `to` parameters are being passed.

the real advantage to using an IIFE is to provide a scope for some variables that will remain for some time. So my above example? Doesn’t make a lot of sense - it’s being used once, the values have been hard-wired, and the lexical scope won’t be used again.

IIFE’s are often used when creating a singleton, or a library of functionality you want to keep around for a while. Running the initial IIFE can initialize the singleton/library, while subsequent calls are simply running some “hooks” into that lexical space.

You can read more about IIFE’s and their use here: https://medium.com/@vvkchandra/essential-javascript-mastering-immediately-invoked-function-expressions-67791338ddc6 - also, scrolling down in there, you’ll see IIFE with parameters. Might help some.

1 Like

Chances are most of the time you can use an ES6 module instead of an IIFE. There’s still a few tricks IIFEs can do that modules can’t, though once you start invoking them multiple times with arguments, you may as well give such a function a name at least. It’s basically a constructor at that point anyway.

1 Like