Ternary Operators for JavaScript

Whats the ruling for using ternary operators in JavaScript? I couldn’t find a specific ruling in the standards documentation. I saw that the Codidact JS Conventions Documentation referencing bracing uses separate if / else blocks, instead of utilizing a ternary operator.

I understand that ternary operators could lead to exceeding the line length rule (120), but that can easily be solved, for example:


this.dataset = Object.keys(data).length > 0 ? 
               data :
               {};

(Assuming that data and {} are longer lines that would result in exceeding 120 characters).

2 Likes

Good call. Added item 10. Conditional assignment, with modifications to the style you proposed. Can you confirm if it looks good?

3 Likes

Does the same principal apply for null coalescence?

var x = obj.property && obj.property.value || 1;

It’s not the same as the following if the value would be falsey.

var x = obj.property ? obj.property.value : 1;

@Marc.2377

Yeah that looks really good, thanks for the clarification and addition!

2 Likes