Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Confuse with ternary operator tutorial on Mozilla website

I don't understand this lines of code:

var condition1 = true,
    condition2 = false,
    access = condition1 ? condition2 ? "Full pie": "Half pie": condition2 ? "Half pie" : "No pie, don't cry" ;

console.log(access); // logs "Half pie"

espesially from the start condition1?condition2? part... Can someone give me a clue of the if-else statement form of this code?? :D Source: https://developer.mozilla.org/id/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Thanks for the help!

3 Answers

Steven Parker
Steven Parker
243,318 Points

Ternaries can be hard to read when combined.

Perhaps some parentheses and formatting will help:

    access = condition1 ?
        ( condition2 ? "Full pie" : "Half pie" ) :          // if condition1 is true
        ( condition2 ? "Half pie" : "No pie, don't cry" );  // if condition1 is false

Now it's easier to see that the ternary that uses condition1 will evaluate one of two inner ternaries that use condition 2 to select the string to assign.

wow, you made my day! thanks :D yeah the magic happen when you give the parentheses So it is like this?

condition1 = true;
condition2 = false;
if(condition1){
  if(condition2){
    console.log("Full pie");
  }
  else{
    console.log("Half pie");
  }
}
else{
  if(condition2){
    console.log("Half pie");

  }
  else{
    console.log("No pie, don't cry");
  }
}

yeah and their website is sometimes don't give full clear explanation

Steven Parker
Steven Parker
243,318 Points

Right, this code is functionally equivalent. And now you can see how ternaries can make code much more compact!

If I were actually writing that ternary expression in real code, I would format it just like I showed above to make it more readable, only I would not add the parentheses.

Thanks, friend for all the info, I always envy when other coders that can write less code like ternary, and write in ternary make our code shorter so less in bug and more readable and it seems like a "pro programmer" wkwkwk