Maintain Readability for Conditional Assignments with JavaScript IIFEs

InstructorAlex Reardon

Share this video with your friends

Send Tweet

This lesson will show you how you can use Immediately Invoked Function Expressions (IIFE's) to make conditional assignments more readable and robust

mister. jones
~ 6 years ago

Very cool. I too often reach for the nested ternary, because I like that it's an expression, despite knowing that it can be hard to reason about. The IIFE definitely works as a good replacement.

However, I also find myself using nested ternaries because I don't like all the "noise" that comes with if-else blocks. Looking at your example, I thought about this for a bit, and wondered, since we're simply checking a conditional and returning a value, maybe something like this inside the IIFE could work as well:

const greeting = (() => {
  const roomStatuses = [
    [isJoiningRoom, 'Welcome'],
    [isLeavingRoom, 'Goodbye'],
    [isEnteringRoom, 'Welcome back'],
    [true, 'Hi'],
  ]
  const roomStatus = roomStatuses.findIndex((element) => element[0])
  return roomStatuses[roomStatus][1]
})()

The logic getting the roomStatus value takes a second to understand versus reading through the if-else block, but I think the readability provided by the roomStatuses array could make it a worthwhile compromise.

Or, if the room status were being tracked as a string, instead of one of several Booleans, we could simplify it a bit with an object literal:

let roomStatus = 'isEnteringRoom'

// See: Replacing switch statements with Object literals | Todd Motto
//   https://toddmotto.com/deprecating-the-switch-statement-for-object-literals/
const greetingFromObject = (() => {
  const roomStatuses = {
    isJoiningRoom: 'Welcome',
    isLeavingRoom: 'Goodbye',
    isEnteringRoom: 'Welcome back',
    default: 'Hi',
  }
  return roomStatuses[roomStatus] || roomStatuses['default']
})()

Here's a jsfiddle of these two implementations in action: Conditional Assignments

Thank you for the inspiration! :)

Bijoy Thomas
~ 6 years ago

You could convert the booleans into strings and use them to index into a lookup like you have above (helper functions from ramda)

// booleans
const
isJoiningRoom = false,
isLeavingRoom = true,
isEnteringRoom = false

const greeting = compose(
  flip(prop)({isJoiningRoom: 'Welcome', isLeavingRoom: 'Goodbye', isEnteringRoom: 'Welcome back', 
    default: 'Hi', }),
  propOr('default', 'true'),
  invertObj
)({isJoiningRoom, isLeavingRoom, isEnteringRoom}) // turn the variables into keys which are strings