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 π
- A working knowledge of JavaScript (i.e. if statements and truthy/falsy expressions)
- 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
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";
}
This if statement is a great opportunity to refactor using ternary operators. Let's break it down step by step.
- Find the condition
(userId.value.length === 10)
- Find the truthy value
userIdValid = "the user ID is valid";
- Find the falsy value
userIdValid = "the user ID is not valid";
- Put it all together using "?" and ":"
(userId.value.length === 10) ? userIdValid = "the user ID is valid" : userIdValid = "the user ID is not valid";
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";
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";
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)
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:
Thanks for the post!
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 π
You might want to use a different example where the variable is of a different type than boolean, e.g.:
Because if the variable itself is a boolean, why not just say:
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:
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:
then I can't help myself and I have to immediately change it to:
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 ...
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 π
Given that === already produces true or false the examples are a bit redundant. :)
Here's another operator taking three operands: a(b, c).
I updated the article to use strings instead! Thanks for the input π
You're welcome.
In my view the insight that is missing in this article is the key difference between both conditional constructs:
if
statement is - well, a statement.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.
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! π¦
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!
Great Post thank you.