DEV Community

Valentina Peric
Valentina Peric

Posted on

Writing If Statements with the Ternary Operator

When I first saw if statements using ternary operators, I was confused. "Why is there a question mark?" and "Why is there a colon?" were probably some of the thoughts I had.

After some research and practice, I was finally getting the grasp on how to take my if statements to the next level using ternary operators.

Prerequisites πŸ“

  1. A working knowledge of JavaScript (i.e. if statements and truthy/falsy expressions)
  2. A code editor (I recommend Visual Studio Code)

Let's Get Started ✨

First, let's breakdown ternary operators using MDN

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.

It looks like this,

condition ? truthy expression : falsy expression
Enter fullscreen mode Exit fullscreen mode

Second, let's take a look at an if statement that could be refactored using the ternary operator

let userIdValid; 

if (userId.value.length === 10) { 
  userIdValid = "the user ID is valid";
}
else {
  userIdValid = "the user ID is not valid";
}
Enter fullscreen mode Exit fullscreen mode

This if statement is a great opportunity to refactor using ternary operators. Let's break it down step by step.

  1. Find the condition (userId.value.length === 10)
  2. Find the truthy value userIdValid = "the user ID is valid";
  3. Find the falsy value userIdValid = "the user ID is not valid";
  4. Put it all together using "?" and ":"
(userId.value.length === 10) ? userIdValid = "the user ID is valid" : userIdValid = "the user ID is not valid";
Enter fullscreen mode Exit fullscreen mode

Notice that you only need the ";" at the very end of the statement.

πŸŽ‰As a bonusπŸŽ‰, you can refactor this even further by assigning the statement to the userIdValid variable like this,

let userIdValid = (userId.value.length === 10) ? "the user ID is valid" : "the user ID is not valid";
Enter fullscreen mode Exit fullscreen mode

Key takeaways ✨

Refactoring this took 8 lines of code and simplified it down to 1 line. This is great! Adding a code comment right above the statement can help explain what is going on. This is helpful for future you and other fellow developers!

//checking the validity of the userId by checking its length
let userIdValid = (userId.value.length === 10) ? "the user ID is valid" : "the user ID is not valid";
Enter fullscreen mode Exit fullscreen mode

And there you have it! You just wrote an if statement using ternary operators.

Next Steps ✨

Take a look at some of the if statements you have already written in past or current projects. Do any of them present an opportunity to be refactored using ternary if statements? If yes, I encourage you to give it a try!

Thanks for reading! Was this article helpful for you? Any ideas that can be shared? Post a comment below!

P.S. This is my first technical blog post! I found a lot of encouragement from reading The Developer's Guide to Content Creation by Stephanie Morillo. I highly recommend it!

Top comments (12)

Collapse
 
sebnitu profile image
Sebastian Nitu • Edited

Great post! I've recently started using ternary operators as well. One "gotcha" I've found when writing them is to not use them in a way that make the line-length too long. Typically I try and keep them under 80 characters, so you can also write your example like this if that was a goal:

let userIdValid = (userId.value.length === 10) ? 
  "the user ID is valid" : 
  "the user ID is not valid";

Thanks for the post!

Collapse
 
valentinaperic profile image
Valentina Peric

Thank you Sebastian - I am glad you enjoyed it! Your refactor is a great reminder that you can use multiple lines for ternaries! Thank you for the addition 😊

Collapse
 
jingxue profile image
Jing Xue

You might want to use a different example where the variable is of a different type than boolean, e.g.:

let msg = (userId.value.length === 10) ? 'length 10' : 'other length'

Because if the variable itself is a boolean, why not just say:

let userIdValid = userId.value.length === 10
Collapse
 
leob profile image
leob • Edited

I agree that the original example (evaluating to true or false) was slightly redundant ... and a bit of a tangential rant: the brackets "()" are redundant as well - the following works fine too:

let msg = userId.value.length === 10 ? 'length 10' : 'other length';

In the past I often worked with people who wrote huge amounts of unnecessary brackets in their expressions, and it always irked me - when I see stuff like this:

if (((a*b)+1) > (c-(d/e))) {

then I can't help myself and I have to immediately change it to:

if (a*b + 1 > c - d/e) {

which means exactly the same thing (because of the priority rules that everyone should have learned somewhere in the 6th grade of primary school). Reads so much better ...

Collapse
 
valentinaperic profile image
Valentina Peric

Yes, you could remove the operand altogether if you wanted to further refactor and simplify the code! This is great. I wanted to show an example that was explicit in the truthy expression and falsy expression. Thanks for the input, Jing πŸ™‚

Collapse
 
pentacular profile image
pentacular

Given that === already produces true or false the examples are a bit redundant. :)

Here's another operator taking three operands: a(b, c).

Collapse
 
valentinaperic profile image
Valentina Peric

I updated the article to use strings instead! Thanks for the input 😊

Collapse
 
pentacular profile image
pentacular

You're welcome.

Collapse
 
peerreynders profile image
peerreynders • Edited

In my view the insight that is missing in this article is the key difference between both conditional constructs:

  • An if statement is - well, a statement.
  • The ternary operator is part of an expression.

So what?

  • An if statement routes the flow of execution - based on the outcome of the condition, program execution is routed to a specific conditional block of statements.

  • A ternary has to produce value - so a ternary expression will always have to have two possible outcomes (values). (BTW - what else returns a value: a function).

If you have an imperative programming style you will be thinking and programming in statements. As such you will default to if statements (me - programming C decades ago and going "yech" every-time I came across a ternary).

Once you start using a functional language (say Erlang, OCaml, Haskell, Elixir, Clojure, etc.) statements go out the window (even Rust, though imperative, is largely expression-based). You have to deal with everything in terms of expressions producing values (not statements mutating values; PLOP - Place-Oriented Programming) because expressions - just like functions - take some values as inputs and produce a new value. There is no if statement - only conditional expressions.

Scheme is in JavaScript's history which is evidenced by its function-oriented nature so while it isn't possible to dump statements entirely (they have their uses 😏) one can develop a more expression-based style - and using ternaries (with tuples and destructuring assignments) is a big part of that.

// ...

function categorize(ch) {
  return 'a' <= ch && ch <= 'z'
    ? CHAR_CATEGORY.LowerCase
    : 'A' <= ch && ch <= 'Z'
    ? CHAR_CATEGORY.UpperCase
    : SEPARATORS.includes(ch)
    ? CHAR_CATEGORY.Delimiter
    : CHAR_CATEGORY.Other;
}

const isAlphabetic = (c) =>
  c === CHAR_CATEGORY.LowerCase || c === CHAR_CATEGORY.UpperCase;

function reducer([last, acronym], ch) {
  const current = categorize(ch);
  return (last === CHAR_CATEGORY.LowerCase &&
    current === CHAR_CATEGORY.UpperCase) ||
    (last === CHAR_CATEGORY.Delimiter && isAlphabetic(current))
    ? [current, acronym + ch.toUpperCase()]
    : [current, acronym];
}

// beginning of phrase is equivalent to a "delimiter"
const INIT_COLLECT = Object.freeze([CHAR_CATEGORY.Delimiter, '']);

function acronym(phrase) {
  const [_last, result] = phrase.split('').reduce(reducer, INIT_COLLECT);
  return result;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mintii profile image
Brittney Braxton

I always appreciate clear examples about code concepts. The way you wrote this is very similar to how I learned and refactored my code to include ternaries. I also took similar steps to take complex ternaries to revert them back into if/else blocks (not everything needs to be a one-liner πŸ˜‚)
I'd love to see your thoughts and approach to refactoring vanilla JavaScript to be more es6 compatible, like the different ways there are now to make a function! πŸ¦„

Collapse
 
valentinaperic profile image
Valentina Peric

ME TOO! They are helpful - thank you! πŸ™‚

& I agree - not everything has to be one-liner. During a code review, I had feedback that my one-liner was long because I got carried away with the refactor πŸ˜‚ (I was using a ternary operand!). Sometimes simplifying code can reduce readability. This is a great reminder, Brittney! Thank you.

Refactoring vanilla JavaScript to be more ES6 compatible - that would be a fun series. I love the idea. I would also be interested in seeing the comparison once an entire project is completely refactored!

Collapse
 
shawn2208 profile image
Shawn2208

Great Post thank you.