DEV Community

Discussion on: Tenary Operators in JavaScript, Should I?

Collapse
 
functional_js profile image
Functional Javascript

Nice comprehensive analysis Osumgba.

I use ternaries when it's a pretty simple conditional and need one of two possible values returned.

They are especially helpful in creating single line functions, for example....

/**
@func
find the largest word in an array

@param {string[]} a
@return {string}
*/
const getLongestStrInArr = a => a.reduce((biggest, curr) => curr.length > biggest.length ? curr : biggest);

//@tests
const aWords = ["a", "abcde", "", "abc", "abcd"];
console.log(getLongestStrInArr(aWords)); // abcde
Collapse
 
osumgbachiamaka profile image
Osumgba Chiamaka

Tenary operators are amazing especially in simple conditioning, but can get completed when you start nesting them.