what's the difference between "ternary"operator and ifelse statement? | SoloLearn: Learn to code for FREE!


what's the difference between "ternary"operator and ifelse statement?

sample1:Ternary operator var myNum1 = 7; var myNum2 = 10; if (myNum1 < myNum2) { alert("JavaScript is easy to learn."); } sample2:Ifelse statement var myNum1 = 7; var myNum2 = 10; (myNum1 < myNum2 ) ? alert("javascript is easy to learn") : "" ;

7/14/2017 12:26:52 PM

Suleyman K.

7 Answers

New Answer


Readability - Use If else or Switch case Reliability - Use ternary operators Speed - Use ternary operators Ternary operators are the shortest path to write a program like comparing 3 numbers , and output the greatest number from them , Eg . A program for this case using if else is more than 8 lines but ternary takes it only 1 line in this way :- a>b?b>c?'a':c>b:'c':'a'; Just that much .. Hope you understand .


its better to use if else because readability use ternary if ur defining functions that u wont see it again for example like lets say u wanna have a function that validates sth, u can do sth like lol=s=>/\d/.test(s)?true:false ok so lol() is a function to validate whether a string contains a number and using ternary is fine



ternary is like a shortcut


Saves ur time


beside the way you write it down :) is there a bestway practice. when to you use ifelse and when the ternary operator?


ternary operator needs to have all it's paths return the same type. if else statement does not have this requirement. but following it as a matter of discipline makes for easier maintenance. you don't want to be spewing expletives at the you from 6 weeks or 6 months ago. however, if you are not returning any value, instead, say doing something like if under 21, add to table x, if 21 or over, add to table o, if else is better. this type of operation that does not return anything and affects the state of the world is called impure operation. this shouldn't have been the case. Kotlin has just if else expressions. No ternary operator, no if else statement.