JavaScript Ternary Operator - When should/shouldn't I wrap my condition in brackets?


This is my first forum question so hope I have added to the correct area! I’m learning about Ternary Operators and wondered when I should or shouldn’t wrap my condition within brackets? For example, in the example found here:

The examples conditions are not surrounded by quotes and are just instead their variable naming which obviously either evaluated to true or false. Is this because they are not needing to ‘calculate/evaluate’ anything before determining whether true or false and instead are just true or false by default.

I wrote this small program where I imagined a log in system. In this example, I wrapped my conditions in brackets because the value is not known until the code runs within the brackets. Here is my code:

let password = 'test123';
let loginStatus = (prompt('What is your password?') === password) ? true : false;

let status = loginStatus;
let alert = (status) ? 'You are now logged in!' : 'Incorrect Password!';


Hope this question makes some sense but in summary, when do I need brackets around the condition and when do I not need brackets.

Thank you!

Are you asking if in this part:

let alert = (status) ? 'You are now logged in!' : 'Incorrect Password!';

it is mandatory to wrap status in parenthesis? As far as I know, no you do not have to. Even when you are checking things like:

let alert = status === 'good' ? 'Good to go' : 'Nope';

it will work!

PS: of course, for ease of reading, you might want to wrap it in parenthesis

Yes, exactly what I was asking. Do you know what is considered best practice?

Thank you for the clear explanation :slight_smile: