Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Apply Multiple CSS-in-JS Arguments in a JavaScript Mixin Function with the Rest Operator


    The rest operator in JavaScript allows us to 'collect' arguments dynamically in one variable similar to SCSS variable arguments

    This is useful for CSS-in-JS when you have CSS properties like box-shadow that can attach multiple shadows to a single element. With the rest operator, you'll be able to add all the shadows you want to a single argument for use in a JavaScript CSS mixin function.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: We have two buttons. One is written using SASS, and the other one is SCSS and JS. Let's have a look at this box-shadow and mixin.

    This mixin accepts a variable amount of shadows. You can pass just one shadow, or you can pass two, same like the native implementation of box-shadow in CSS.

    Let's have a look at the mixin itself. Here is the box-shadow mixin. We use here a SASS feature, which is called variable arguments. It allows us to just name one argument without knowing how many of them will be passed.

    To use it like a regular variable, this mixin allows us to generate vendor prefixes. Let's see how we can implement the same thing in JavaScript.

    Here we have our SCSS rule. Here are the box-shadow function/mixin call. Same like in SASS, we can pass one argument, two arguments, or basically an unlimited amount of arguments.

    Let's have a look at the mixin implementation itself. Here, we have our mixin function declaration. We assign this function to a box-shadow constant. We export this constant. Then we declare the function.

    First interesting thing about this function is the arguments. These three dots before the argument is called rest operator. Rest operator in JavaScript works exactly the same way like variable arguments in SASS.

    The interesting part is how we use the shadows array. JavaScript language has a feature called coercion. We just created the shadows array to demonstrate what happens within array inside of our mixin.

    Our mixin is a template string. If we use a variable inside of a template string which is not a string, JavaScript will always try to course this variable to a string.

    In our case, the result of a coercion is a string where red and green is comma-separated.