DEV Community

Discussion on: ELI5: Why use a function declaration, expression, or an IIFE in JavaScript?

Collapse
 
jckuhl profile image
Jonathan Kuhl • Edited

I did find an interesting use case for an IIFE the other day.

I wanted an array of emojis. I got them from EmojiCopy and I copied them as a string. I didn't want however to write them all down one by one to create an array. What I needed instead was a function that is immediately invoked and turns my string into an array. What makes this difficult, is that I can't use split('') because an emoji is technically two characters, not one.

So I used an IIFE to create my array:

const faces = (() => {
    const faces='๐Ÿ˜€๐Ÿ˜ƒ๐Ÿ˜„๐Ÿ˜๐Ÿ˜†๐Ÿ˜…๐Ÿ˜‚๐Ÿคฃ๐Ÿ˜Š๐Ÿ˜‡๐Ÿ™‚๐Ÿ™ƒ๐Ÿ˜‰๐Ÿ˜Œ๐Ÿ˜๐Ÿฅฐ๐Ÿ˜˜๐Ÿ˜—๐Ÿ˜™๐Ÿ˜š๐Ÿ˜‹๐Ÿ˜›๐Ÿ˜๐Ÿ˜œ๐Ÿคช๐Ÿคจ๐Ÿง๐Ÿค“๐Ÿ˜Ž๐Ÿคฉ๐Ÿฅณ๐Ÿ˜๐Ÿ˜’๐Ÿ˜ž๐Ÿ˜”๐Ÿ˜Ÿ๐Ÿ˜•๐Ÿ™๐Ÿ˜ฃ๐Ÿ˜–๐Ÿ˜ซ๐Ÿ˜ฉ๐Ÿฅบ๐Ÿ˜ข๐Ÿ˜ญ๐Ÿ˜ค๐Ÿ˜ ๐Ÿ˜ก๐Ÿคฌ๐Ÿคฏ๐Ÿ˜ณ๐Ÿฅต๐Ÿฅถ๐Ÿ˜ฑ๐Ÿ˜จ๐Ÿ˜ฐ๐Ÿ˜ฅ๐Ÿ˜“๐Ÿค—๐Ÿค”๐Ÿคญ๐Ÿคซ๐Ÿคฅ๐Ÿ˜ถ๐Ÿ˜๐Ÿ˜‘๐Ÿ˜ฌ๐Ÿ™„๐Ÿ˜ฏ๐Ÿ˜ฆ๐Ÿ˜ง๐Ÿ˜ฎ๐Ÿ˜ฒ๐Ÿ˜ด๐Ÿคค๐Ÿ˜ช๐Ÿ˜ต๐Ÿค๐Ÿฅด๐Ÿคข๐Ÿคฎ๐Ÿคง๐Ÿ˜ท๐Ÿค’๐Ÿค•๐Ÿค‘๐Ÿค ๐Ÿ˜ˆ๐Ÿ‘ฟ๐Ÿ‘น๐Ÿ‘บ๐Ÿคก๐Ÿ‘ฝ๐Ÿค–๐ŸŽƒ';
    const faceArray = [];
    for(let index = 0; index < faces.length; index += 2) {
        let face = faces[index] + faces[index+1]
        faceArray.push(face)
    }
    return faceArray
})();
Enter fullscreen mode Exit fullscreen mode

Now granted, I could have saved that IIFE as its own function and then called it, but I don't need to call it more than ones so why make a reference to a function I only need to ever use once?

Collapse
 
somedood profile image
Basti Ortiz

This is definitely a valid use case for it. I guess the only problem you'll ever face with this approach is readability. At first glance, it isn't really a design pattern you see often. Moreover, the algorithm isn't as straightforward as one may think. Perhaps sprinkling a few comments here and there explaining your rationale and thought processes will help. Other than that, I see nothing wrong with this. ๐Ÿ™‚

Thread Thread
 
sebvercammen profile image
Sรฉbastien Vercammen • Edited

That's because it's an anti-pattern. This is not a valid use case.

  1. An interpreter already executes code, so you don't need to wrap it in a function. Remove the function, and you've got the same output.
  2. If you need to repeat execution, you should define a function with a descriptive name.
  3. In this case, the result will always be the same, and the whole function can be replaced with its output to save on execution time.

An IIFE is still common. It's often used in browser
content extensions or snippets loaded from providers (analytics, ads, ...), because the browser's scope is shared by all active snippets, so we limit the scope.

Thread Thread
 
somedood profile image
Basti Ortiz

Well, there's that, too. ๐Ÿ˜…

Collapse
 
gmartigny profile image
Guillaume Martigny

Hey, I just want to point out that you can do the same with:

const faces = "๐Ÿ˜€๐Ÿ˜ƒ๐Ÿ˜„".match(/.{2}/g);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ˜Ž