Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator should not be used on a single line in Node.js. Why?

Consider the following sample codes:

1.Sample

var IsAdminUser = (User.Privileges == AdminPrivileges)
  ? 'yes'
  : 'no';
console.log(IsAdminUser);

2.Sample

var IsAdminUser = (User.Privileges == AdminPrivileges)?'yes': 'no';
console.log(IsAdminUser);

The 2nd sample I am very comfortable with & I code in that style, but it was told that its wrong way of doing without any supportive reasons.

Why is it recommended not to use a single line ternary operator in Node.js?

Can anyone put some light on the reason why it is so?

Advance Thanks for great help.

like image 469
Amol M Kulkarni Avatar asked Dec 04 '22 00:12

Amol M Kulkarni


1 Answers

With all coding standards, they are generally for readability and maintainability. My guess is the author finds it more readable on separate lines. The compiler / interpreter for your language will handle it all the same. As long as you / your project have a set standard and stick to it, you'll be fine. I recommend that the standards be worked on or at least reviewed by everyone on the project before casting them in stone. I think that if you're breaking it up on separate lines like that, you may as well define an if/else conditional block and use that.

Be wary of coding standards rules that do not have a justification.

Personally, I do not like the ternary operator as it feels unnatural to me and I always have to read the line a few times to understand what it's doing. I find separate if/else blocks easier for me to read. Personal preference of course.

like image 150
Stealth Rabbi Avatar answered Jan 17 '23 16:01

Stealth Rabbi