Create a List of Toggle-able Settings in JavaScript

A bite-size blog post on a JavaScript problem I could not Google.

Brad Dunn
3 min readJan 30, 2018

On a recent project I was playing with I had a need for maintaining a list of settings that had an on/off or true/false nature to each list item. Although I ultimately found what I needed buried in a few code snippets on the React Native documentation, it took me considerable effort to find what I was looking for by googling. I figured writing a quick article may be helpful to other programmers with this need as well as a quick reference for my future self.

The problem

Need to efficiently and easily track boolean states for a list of properties.

The solution

JavaScript’s Map object.

Notice that I'm talking about the upper-case ‘M’ap object and not the map method available on strings and other iterable objects in JavaScript. The standalone map object holds onto key-value pairs, which is really well suited for our problem set described above. In order to illustrate the power of the solution, let's take a look at a more basic and naïve solution first:

This does the job but there's several problems with this approach. For one its pretty flimsy. If we make a mistake and try to update a preference that's unavailable in the preferences object at run-time, we're going to throw an error and crash and burn. To solve this problem we could throwing some error handling code to check the existence of a key before trying to toggle the value. But even with this change we would have to maintain the preferences objects manually and this becomes very inflexible if we want to efficiently react to future business changes.

Instead, we could reach for the aforementioned Map object, which solves most of the problems mentioned above.

With this version we don't have to worry about whether not a particular preference has been selected. We don't even really need to care about what the preferences are called in advance. The Map.get() will return true if the preference exists and false if it either doesn't exist or is actually set to false to begin with. This cleanly takes care of both of our issues and gives us a very nice interface to interacting with this preference list.

If you wanted to take this further and use it for say a setting screen on a Reactive Native app, you can use this in conjunction with FlatList (Similar to the way Facebook suggests on their React Native documentation):

I encourage you to look at the full example on the actual documentation page for FlatList.

I hope this little tip is helpful to someone out there!

Side note: I wrote this entire article using Mac’s dictation software so if you see any inaccuracies in my grammar please leave a comment or highlight the mistake. I appreciate it!

Further Reading:

--

--