I read an e-book and find this command, but I don’t know it’s purpose and when to using it. Example:
var x = (12, 34, 56)
x in this case is a number and it’s value is 56. Thanks.
This is the full script I read from ebook ‘Javascript for absolute Beginners’:
var fridge = {
buttermilk: [1/3, "cup"],
kefir: [1 + 1/2, "cup"],
yogurt: [4, "cup"],
};
var dough = {
hardWhiteWholeWheatFlour: [2, "cup"],
sugar: [1/3, "cup"],
madagascarVanilla: [1, "tsp"],
orangeZest: [1, "tbs"],
soda: [1, "tsp"],
tartar: [1, "tsp"],
orangeJuice: [1/2, "cup"],
culturedMilk: [1/2, "cup"],
egg: [1],
cranberries: [2/3, "cup"]
};
dough.culturedMilk[0] = fridge.buttermilk[0] >= 1/2 ? (fridge.buttermilk[0] -= 1/2, 1/2) :
fridge.kefir[0] >= 9/16 ? (fridge.kefir[0] -= 9/16, 9/16) :
fridge.yogurt[0] >= 10/16 ? (fridge.yogurt[0] -= 10/16, 10/16) :
alert("No cranberry bread for you!");
dough.culturedMilk;
// [0.5625, "cup"]
fridge.kefir;
// [0.9375, "cup"]
It seems you already know what it means… evaluated each operand and return the result of the last.
In the case of
(fridge.buttermilk[0] -= 1/2, 1/2), the expression itself is part of the conditional operator:In this case, the comma operator is used to introduce side effects. If
fridge.buttermilk[0] >= 1/2is true, then1/2should be assigned todough.culturedMilk[0]. But at the same time,fridge.buttermilk[0]should be updated as well.Normally you would use two expression statements, like
but since the author wants to use the conditional operator, the comma operator can be used to execute both expression in one expression. It updates the value of
fridge.buttermilk[0]and returns1/2.I’m not recommending doing this though, especially in this case, with nested conditional operators, a traditional
if-elsestatement would be easier to read.