DEV Community

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

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I used an IIFE recently to make computed properties on an object literal.

Given the following code:

attachEvent({
click: "some-element",
});

Now imagine I want that 'some-element' to be conditional. In this circumstance for the framework I'm using I cannot do this in a traditional way, that method is part of a class.

So I do this.

attachEvent((() => {
cont day = this.day; // value is wed
return {
click: day === 'thurs' ? 'some-element' : 'another-element';
}
})());

The result is a button that only works on Thursdays. The object was built up and returned in place by the IIFE. It was an edge case but it's certainly one way of doing it.

Very terse code though and maybe not great for your team.