I have just written this code for toggling between two possible states of an object.

// This can't change, and only ever has two states
const MODES = {
  ON: 'ON',
  OFF: 'OFF'

// this is my method
const toggleMode = currentMode => {
  const modes = Object.values(MODES);
  const newMode = modes.find(mode => mode !== currentMode);
  return newMode

// toggle state
const firstState = MODES.ON;
const secondState = toggleMode(firstState);
const thirdState = toggleMode(secondState)

Is this a good way of toggling between the two states? I'm concerned it's less readable than the verbose if one state, then pick the other, else pick the current state. But this way also means that so long as we know there's only two states, then nothing needs to be hardcoded in the function doing the toggling.

  • 1
    \$\begingroup\$ Could you show us how you'd use that code in action? \$\endgroup\$
    – dfhwze
    Sep 3 '19 at 12:06
  • \$\begingroup\$ @dfhwze how much context do you need? The way it's used in the snippet isn't far off. \$\endgroup\$
    – Pureferret
    Sep 3 '19 at 12:07
  • \$\begingroup\$ I can see it toggles, but how would you end up using 'ON' and 'OFF' on an object? \$\endgroup\$
    – dfhwze
    Sep 3 '19 at 12:08
  • 1
    \$\begingroup\$ I have no further questions, your honor. \$\endgroup\$
    – dfhwze
    Sep 3 '19 at 15:27

You currently only print the currently selected mode to the console, but you probably will use this mode for other purposes, such as the business logic of your application. To that end, I suggest splitting the toggling logic from the presentation and use booleans to store the value which you can easily use for branching depending on the currently selected mode.

// Logic: Define the two modes and toggling logic
const MODES = { ON: true, OFF: false }
const toggleMode = currentMode => !currentMode;

// Presentation: Display a selected mode
const displayMode = currentMode => currentMode ? 'ON' : 'OFF';

// Demo
const firstState = MODES.ON
const secondState = toggleMode(firstState);
const thirdState = toggleMode(secondState);

  • \$\begingroup\$ This is a clever distinction, but I don't' think it applies in my case as I'm not going to be displaying the state (the console logs were just to show the function working). I'm also not keen on(sort of) handling two lots of state/processes to get to state. \$\endgroup\$
    – Pureferret
    Sep 4 '19 at 8:11
  • \$\begingroup\$ All the better, if you don't need to display it. The toggling function can be used stand-alone and you can alway check either against truthiness (if(firstState){ … }) or against the "Enum" (if(firststate == MODES.ON){ … }) so not to depend on the inner value. \$\endgroup\$
    – gitcdn
    Sep 4 '19 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.