DEV Community

loading...

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

Collapse
citguy profile image
Ryan Johnson

Personally, I favor function declarations. However, if the logic is simple enough, I'll consider using a function expression using an arrow function (typically for functional composition).

Both of these are functionally equivalent:

const isTruthy = (item) => item

function isTruthyLong (item) {
  return item
}

When you use them as the callback for array.filter() they behave the same.

let a = Array(3) // [undefined, undefined, undefined]
a[1] = 'Hi mom!'
let short = a.filter(isTruthy)
let long = a.filter(isTruthyLong)
console.log(a) // [undefined, 'Hi mom!', undefined]
console.log(short) // ['Hi mom!']
console.log(long) // ['Hi mom!']

CodePen Demo

Forem Open with the Forem app