2

Javascript

var x = y || z (logical-or operator)

x = y if y is not falsy, otherwise z 

What's the SASS/SCSS equivalent of Javascript's "var x = y || z"?

dragonmnl
  • 14,578
  • 33
  • 84
  • 129
  • 1
    A quick google search for **"sass assign default value to variable if undefined"** lead me to the official docs about default variables: https://stackoverflow.com/questions/3525007/making-a-sass-mixin-with-optional-arguments – Justin Taddei Jan 27 '21 at 19:42
  • Your explanation of `var x = y || z` is not entirely correct. `y` may be defined as a falsy value, and in that case the value in `z` will end up in `x`. Also, if `y` is not defined your code will encounter a Reference Error. – edo.n Jan 27 '21 at 19:52
  • 1
    @edo.n good point. I will update the question – dragonmnl Jan 27 '21 at 19:54

3 Answers3

3
$x = if(variable-exists('y'), $y, $z);`

Docs for variable-exists

vsync
  • 118,978
  • 58
  • 307
  • 400
Joundill
  • 6,828
  • 12
  • 36
  • 50
3

The !default flag, will have this variable skipped, if it already exists.

For example:

$var: foo;
$var: bar !default;

@debug $var; // foo

And:

$var: bar !default;

@debug $var; // bar

Update: since you clarified your question, this might be a better approach:

@function return($x, $y) {
  @return if(($x != false), $x, $y);
}

@debug return("foo", "bar"); // "foo"
@debug return (false, "bar"); // "bar
Simplicius
  • 2,009
  • 1
  • 5
  • 19
0

Double-pipe Operator

This construct is called "double-pipe operator" in JavaScript, and helps a lot in writing readable and clean code.

But I don't think SASS have something like it, sadly. The closest you can get to it is by using default values with the !default tag or the @if and @else flow controls.

  • It is the "Logical OR" operator in Javascript; it's written as a double-pipe but it is not _called_ the "double-pipe" operator. It's _called_ the logical-or operator. – Stephen P Jan 27 '21 at 19:53