Search code examples
csssass

why sass doesn't return the value of a global variable which I had Modified it inside a function?


I was practicing with sass @function and I realized when my variable is global scope the function doesn't apply changes to this variable and just return its initial value but when I declare this variable as function scope, changes get applies on this variable without any problem and function returns the expected value, so I was wondering why this is happening in the first situation?

code:

//first situation


$s:8;
@function lome($a...){

@each $i in $a{
$s:$s+$i;
}
@return $s;
}

@debug lome(1,2,3);

//expected output:14;
//output:8;
//second situation

@function lome($a...){
$s:8;
@each $i in $a{
$s:$s+$i;
}
@return $s;
}

@debug lome(1,2,3);

//expected output:14;
//result:14;

Solution

  • Short answer: It's a matter of scope.

    @function lome($a...){
        @each $i in $a{
            $s:$s+$i;
        }
        
        @return $s;
    }
    

    Variables declared in blocks (like the @each) are usually local, and can only be accessed within the block they were declared.

    What's tricky is that local variables can be declared with the same name as a global variable. You're creating a new local variable in the @each block but you're returning the global variable.

    Quick test that would give you the proper result and that won't update the global variable:

    @function lome($a...){
        $x: $s;
        @each $i in $a{
            $x:$x+$i;
        }
        
        @return $x;
    }
    

    If you really want to update the global variable each time you use the function, you can use the flag !global:

    @function lome($a...){
        @each $i in $a{
            $s:$s+$i !global;
        }
        
        @return $s;
    }
    

    More information on the sass documentation.