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

Leandro Severino
Leandro Severino
12,674 Points

Best situation to use the Ternary Operator?

Hi guys. I just want to know when do you usually use the Ternary Operator rather than the usual if statement?

My code below works but do you think its a good practice to do it this way?

this.muzzleVelocity < maxMuzzleVelocity ? this.muzzleVelocity += 1 : console.log("Can't go over the max ");

1 Answer

My impression was to use the ternary when that made it simpler to read. But if doing the usual if... made it clearer, do so.

Leandro Severino
Leandro Severino
12,674 Points

Thanks John! I also go for readability first rather than premature optimization. I just wanted to know what other developers think and maybe I can learn something I don't know yet. Good to know your thoughts on the subject.