DEV Community

Discussion on: Javascript Tips for Beginners

Collapse
 
dansilcox profile image
Dan Silcox

Great tips for someone just getting started and mostly relevant to other languages not just JS!

One thing I would suggest not to use is the nested ternary operators as that really hurts readability - got to remember that as developers we should be optimising mostly for other humans to be able to read our code, not simply machines (or we would write 1s and 0s directly, right!)

Maybe another option would be to put the second ternary inside a temp variable on a separate line, e.g:
‘’’
const x = 10;
const notTen = x === 9 ?
“x is 9” :
“x is not 10”;
const logStmt = x === 10 ?
"x is 10" :
notTen;

console.log(logStmt);
‘’’
(Apologies for formatting, typing on mobile!)

Collapse
 
hb profile image
Henry Boisdequin

Great tips! I agree that the nested ternary operators are confusing but I just wanted to show that an if, else if, and else statement is possible with ternary operators. The way you did it is much cleaner.