UX Design and Development course

What is a function?

A function is a series of calculations or processes that is performed and the return object is something that is consumed by the style, mixin, or variable. A function performs a transaction on one or more arguments that have been passed to the function. A function by definition will return a certain value. Similar to mixins Sass functions can have arguments with default values set and similar to mixins it is best practice to set default values for the arguments that will be commonly used.

Sass comes with some already built-in that are very powerful and in itself can help with most of the commonly used functions. Let's explore the built-in functions.

Writing a function

To construct a function, the syntax is pretty simple. Using the @function directive, assign the function a name and using parens () pass in the argument(s). The key to using a function is that the processes within will output a value that is usable by other features of the language. To do this, use the @return directive within the function.

@function the-name($arg, $arg) {
  ...
  @return
}

Using a function

Either using a core function included in the language or a custom one you created, the primary use is to append the function to another feature as the returned value.

For example, let's say that you need to consume values from variables and are not always sure that they will be the correct values we need for conversion? A very common function in Sass is to convert your pixel values into ems:

@function px-to-em($target, $context) {
  @return ($target / $context * 1em);
}

Using this function, we could pass in 12px and 16in:

SCSS

block {
  width: px-to-em(12px, 16in);
}

CSS

block {
  width: 0.00781em;
}

While Sass can accurately convert these values, this is not the return we are looking for. Let's create another function that will strip away the measurement units and then allow the px-to-em function to return the value we are looking for.

@function strip-units($val) {
  $construct: ($val / ($val * 0 + 1));
  @return $construct;
}

With this added, we can now update the px-to-em function to use this new function:

@function px-to-em($target, $context) {
  @return (strip-units($target) / strip-units($context) * 1em);
}

This will now return the following CSS:

block {
  width: 0.75em;
}

In these examples you can easily see how functions play a role in creating more intelligent CSS rules. By themselves, they are very powerful in running through a series of tasks and returning a value. With their ability to include other functions, or be included within mixins, functions increase modularity and re-usability of code.