Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would one use a logical AND expression (using the `&&` operator, double ampersand) as a stand-alone statement?

What does cinnamon && (this.cinnamon = [1, "stick", "Saigon"]) mean? I understand the first line above it. The second line seems to be doing a comparison operator with &&, but does not assign it to any variable.

var VanillaBean = function (vanilla, cinnamon) {
  this.vanilla = [1, "bean", vanilla ? vanilla : "Madagascar Bourbon"];
  cinnamon && (this.cinnamon = [1, "stick", "Saigon"]);  //?????
};

VanillaBean.prototype = {
  heavyCream: [1, "cup", "Organic Valley"],
  halfHalf: [2, "cup", "Organic Valley"],
  sugar: [5/8, "cup"],
  yolks: [6]
};

var vanilla = new VanillaBean("Tahitian", true);
console.dir(vanilla);
like image 384
user1929393 Avatar asked Oct 31 '25 01:10

user1929393


1 Answers

The line:

cinnamon && (this.cinnamon = [1, "stick", "Saigon"]);

Is equivalent to:

if (cinnamon) {
    this.cinnamon = [1, "stick", "Saigon"];
}

The short-circuiting nature of the logical AND operator is sometimes used this way, since the resulting code is shorter than a full if statement.

That said, I would personally discourage writing code like this, as it is less readable and maintainable than an if statement.

like image 178
Frédéric Hamidi Avatar answered Nov 01 '25 15:11

Frédéric Hamidi