DEV Community

loading...
Cover image for Ternary Operators Syntax Comparison - C++ vs Python vs JavaScript

Ternary Operators Syntax Comparison - C++ vs Python vs JavaScript

devdios profile image Sachin 👨🏻‍💻 ・1 min read

Ternary Operators also known as conditional expressions are an elegant and succinct method to replace if-else statement in programming. These operators evaluate something based on a condition being true or not.

In this post, We'll see the different syntax in which ternary operators in implemented in C++, Python and JavaScript.

Consider the following code snippet,

num = int(input('Enter a number please: '))
if num % 2 == 0: 
    print('num is even')
elif: 
    print('num is odd')
Enter fullscreen mode Exit fullscreen mode

This code checks if the inputted number is even or odd.

With ternary operator, we can reduce the above if else statements with a one-liner code.

In Python,

# syntax
# [on_true] if [expression] else [on_false]

num = int(input('Enter a number please: '))
print('num is even') if num % 2 == 0 else print('num is odd')
Enter fullscreen mode Exit fullscreen mode

In C++

// syntax
// expression ? [on_true] : [on_false]

int num;
cout << "Please Enter a number: " << endl;
cin >> num;
num % 2 == 0 ? cout << "Num is even" : cout << "num is odd";

Enter fullscreen mode Exit fullscreen mode

In JavaScript

// same syntax as C++
// expression ? [on_true] : [on_false]

let num = prompt('Please Enter a number: ')
num % 2 == 0 ? alert('num is even') : alert('num is odd')
Enter fullscreen mode Exit fullscreen mode

Thus, if the expression to be evaluated is small, then ternary operators can prove to be a viable one-liner alternative.

Discussion (0)

pic
Editor guide