Article: Sass Maps vs. Nested Lists

Extract from SitePoint article “Sass Maps vs. Nested Lists” by James Steinbach

Published July 14, 2015

The title of this post may be surprising to some of you. If you are a Sass veteran, you may remember the days (pre-Ruby-Sass-3.3) of using lists of lists to emulate nested arrays of data. (Ruby) Sass 3.3 added a new data type called maps. Lists of lists could hold complex data in a nested format, but without key-value pairing. Maps added key-value pairs and let us create arrays of data.

With the advent of maps, many of us Sass users started putting everything into maps (and for good reason!). All your breakpoint widths, color values, grid layouts, type scales and other responsive typography details can go into maps!

Now that Sass has maps with key-value pairs, is there a good reason to use a list of lists? One theoretical reason would be backwards-compatibility: if your Sass might be maintained by a developer with an older version installed, lists will help them. In practice, however, Sass versions are often controlled by a package.json or other project config, and the Ruby gem can be updated with just one command (gem update sass).

A more practical reason that you might choose to use nested lists instead of a map is typing less. Let’s compare a map and a nested list to see how they compare in their own syntax, and in how we’d loop through them.

Comparing Syntax

For our example, let’s create a data structure that controls responsive typography. It will store four breakpoints (well, one is the default smallest view). For each breakpoint, we’ll store min-width, max-width, a base font-size, and a base line-height.

Complex Map Syntax

Here’s how we’d store that data in a map. One large map will contain four keys (breakpoint labels) whose values are maps of the variables we need to store and use. In a readable format like this, we’ve got a little more than 450 characters and 26 lines.

$breakpoint-map: (
  small: (
    min-width: null,
    max-width: 479px,
    base-font: 16px,
    vertical-rhythm: 1.3
  medium: (
    min-width: 480px,
    max-width: 959px,
    base-font: 18px,
    vertical-rhythm: 1.414
  large: (
    min-width: 960px,
    max-width: 1099px,
    base-font: 18px,
    vertical-rhythm: 1.5
  xlarge: (
    min-width: 1100px,
    max-width: null,
    base-font: 21px,
    vertical-rhythm: 1.618

Nested List Syntax

The nested list for storing this same data is much shorter. We no longer have keys attached to our data however, so we have to rely on looping through it, or calling it with nth() functions. That said, it’s much shorter than the map: less than 180 characters and only 6 lines.

Continue reading article on SitePoint …

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.