Alex Alex - 3 months ago 10
Sass (Sass) Question

Sass - What's the difference between map-get and simple variable?

I'm new with Sass stuff and I've been reading about different ways to use variables, this principle I'm trying to apply is just for colors, some of the solutions I've found were something like this (map-get):

$colors: (
lighestGray: #F8F8FA,
lightGray: #A5ACBA,
light: #FFFFFF,
dark: #000000,
link: #428bca,
linkHover: #555,
navBlue: #7AC243,
navGreen: #009CDC,
);


Then you use it on your class like this:

.my-class {
color: map-get($colors, dark);
}


And the other way is to use:

$color-black: #000000;


Then you use it like this:

.my-class {
color: $color-black;
}


My question is, which option is better? or
map-get
function has another purpose?, has Sass a pattern for this or it depends on each web-developer?.

Thanks for helping me out!.

Regards.

Answer

The differences is that when you use $map variables, they are best designed for using through iterations or using @each.

Sample case:

SCSS

// Map variable
$icons: (
  facebook   : "\f0c4",
  twitter    : "\f0c5",
  googleplus : "\f0c6",
  youtube    : "\f0c7"
);

// Mixin doing the magic
@mixin icons-list($map) {
  @each $icon-name, $icon in $map {
    @if not map-has-key($map, $icon-name) {
      @warn "'#{$icon-name}' is not a valid icon name";
    }

    @else {
      &--#{$icon-name}::before {
        content: $icon;
      }
    } 
  }
}

// How to use it
.social-link {
    background-color: grey;
    @include icons-list($icons);
}

CSS

// CSS Output

.social-link {
  background-color: grey;
}
.social-link--facebook::before {
  content: "";
}
.social-link--twitter::before {
  content: "";
}
.social-link--googleplus::before {
  content: "";
}
.social-link--youtube::before {
  content: "";
}

This code was taken from my own answer in the following post but the answer is a case use of @each :)

Hope this help you