Contact!

String interpolation in JavaScript, Sass and scss

String Interpolation JS, SCSS, SASS

String interpolation is fancy ‘programmer’ talk for injecting variables into strings. Most programming languages have a way of doing this and we are going to have a look at JavaScript and Sass/scss in this post.

In JavaScript you are probably used to seeing strings handled like:

const variable1 = 'hello';
const variable2 = 'world';

console.log(variable1 + " " + variable2); // Output: 'hello world'

In ES6 we can use interpolation to make the code more human readable. The above example becomes something like this:

console.log(`${variable1} ${variable2}`); // Output: 'hello world'

Sass is no different to this and it actually becomes fundamental to use interpolation if we want to work with CSS variables.

body {
    background-color: var(--some-css-variable, blue);
}

$colour: #fff;

body {
    --some-css-variable: #{$colour};
}

This works in the same way if we want to use Sass variables inside of strings:

$themeColour: "red";

body {
    background-color: blue;

    &[theme="#{$themeColour}"] {
        background-color: red;
    }
}

Join the discussion!

You might like: