Last Updated: February 25, 2016
·
2.067K
· lukaszwiktor

smart javascript state toggle

I'd like to share a simple construct that will make your code more concise and allow you to get rid of some if statements.

Let's assume we have two states and we want to switch between them. If current state is A then we want to switch to B and vice versa - from B switch to A. The traditional code for that would be:

if (state == 'A') {
  state = 'B'
} else if (state == 'B') {
  state = 'A'
} else {
  state = undefined;
}

A tricky way to achieve it is:

var toggle = {'A': 'B', 'B': 'A'};
state = toggle[state];

I guess such construct works not only in javascript but also in several other languages.

2 Responses
Add your response

var toggle = {'a':'b', 'b':'c', 'c':'a'}

would give me three states. Lovely.

over 1 year ago ·

That's a state machine there :P

over 1 year ago ·