Ternary Operator Question


#1

Hi all,

I’m building a multiply function that multiplies the values of an array together. This is for the javascript exercises in WebDev 101.

Here’s the solution:

function multiply(array) {
return array.length
? array.reduce((accumulator, nextItem) => accumulator * nextItem)
: 0;
}

I’m confused about how the ternary operator is working here. Doesn’t the “?” have to be preceded by a condition? How is returning array.length a condition? It doesn’t seem like it is a true or false, or coerces to a boolean value. Am I missing some shorthand?

Also, where does it show the variable that 0 is being set to if the condition is false?

Any help or resources you can point me to would be greatly appreciated :slight_smile:


#2

Straight from the MDN documentation:

condition ? exprIfTrue : exprIfFalse 

array.length can evaluate to true or false depending on whether or not it contains anything.

  • If the condition evaluates to true, then the exprIfTrue part of the code runs.
    “All values are truthy unless they are defined as falsy.” So any number except 0 would evaluate to true.
    Therefore, if an array with anything inside of it is passed as an argument to the multiply() function, then that condition is true and the array.reduce(...) code is run.

  • If array is empty, then its length is 0, which would run the exprIfFalse part of the ternary, since 0 is a falsy value. The exprIfFalse part of the ternary operator in this case is simply 0. So it would return 0.


#3

Thanks, Eduardo!


#4

Let me know if you still need help or further clarification :}