? and :

Kevin Kawai
Jul 30, 2017 · 1 min read

While refactoring my old code I came across some methods to shorten simple if else statements. I saw a lot of code online using ? with : to create short one liners but until recently I wasn’t 100% how these worked. I knew that you could use ? to indicate a boolean with methods such as include? but how does this work with :???.

The colon used with a question mark allows you to create a simple if else statement. You write what you want to check before the question mark and write the code body for true on the left of the colon and on the right for false. In this way you can shorten a simple if else statement.

test = true
test ? "true":"false"
==> "true"
test = false
test ? "true":"false"
==> "false"

In Javascript the logical check works for anything that can be tested a truthy value such as the existence of an argument within a function. (this doesn’t work in Ruby).

def test(n)
n ? "argument is #{n}":"no argument"
end
test(1) ==> argument is 1
test() ==> no argument
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade