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
Love Kenly
3,016 PointsTernary Mistery
ok so this ternary operator in JavaScript ? : is a bit different .... so the question is (true)?((function(){console.log("AHH!");console.log("Oooh!");})()):""
- why this works AND (true)?{console.log("AHH!");console.log("Oooh!");}:""
- why this doesn't? we are told that these braces { } are used to group multiple statements into one statement, so, why the 2 statements I wrote aren't grouped into one in the second try ?
2 Answers
Steven Parker
243,656 PointsThe termary operator takes 3 operands.
They are the condition, the true expression and the false expression. The entire thing returns a value, but it is not a complete statement in itself, no more than "count < 8" would be.
The expression operands are not intended to be statements, though statements can be part of an expression. That's why your first example works, you enclosed your statements in an IIFE, which is an expression. But the second example doesn't work because grouping statements in braces still counts as a statement, not an expression.
But both of these are examples of very bad programming practices that should be avoided. Termaries should not be used to control execution flow. Even it if works, it can make the code extremely difficult to understand when read later.
Landon Lung
5,972 PointsTernaries can be thought of like this.
(CONDITION) ? IF_TRUE_DO_THIS : OTHERWISE_DO_THIS;
Example
var i = 5;
function check(){
return ((i > 3) ? 'Higher' : 'Lower');
}
check();
Would return Higher since i is greater than 3.
The reason (true)?((function(){console.log("AHH!");console.log("Oooh!");})()):"" works is the double parens at the end tell it to run the function console logging the result since true is being returned from the condition.
The reason the second one doesn't work is the {} are telling it to return a object in this case.
var test = (true) ? {} : "";
typeof test
will return "object"
var test = (true) ? { console.log('AHH!') } : "";
will error since this is not a valid object.
Wrapping things in {} works in ES6 to group things.
Example: (enter this in your console)
{
console.log("AHH!");
console.log("Oooh!");
}
You just can't return that from a ternary operator. Normally it's used to return a value not a entire function or a object.
Hope this helps some.