re: ELI5: Why use a function declaration, expression, or an IIFE in JavaScript? VIEW POST


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

Given the following code:

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 =; // 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.

code of conduct - report abuse