Did You Know There’s an Elvis Operator?

What other clever operator names are out there?

Jonathan Hsu
Nov 18 · 3 min read
Photo by Greg Ortega on Unsplash

After Python 3.8 released the Walrus Operator and I began experimenting with it, I couldn’t help but be impressed with the creativity in naming. I mean, it really does look like a walrus. So I asked myself the question: what other clever operator names are out there?

This led me to the Elvis operator, ?:, which is named after its resemblance to his famous hair. While I can’t say this is the “king” of operators, I found it valuable enough to share.


What Is the Elvis Operator?

Also called a null-safety, the Elvis operator will take the first of two operands if that value’s boolean expression is true; otherwise, the second value is taken.

// example is language agnostic
// assume variable 'a' is null
// This would store the default string
my_var = a ?: "a default string"

The intention of the Elvis operator is to condense a ternary operator statement where the boolean evaluation of the “if true” value is the determinant expression.

// examples are language agnostic// ternary example
my_var = a ? a : b
// expanded if/else example
if(a) {
my_var = a
} else {
my_var = b
}

Does My Language Have the Elvis Operator?

In PHP’s implementation of the ternary operator, the middle operand may be omitted, in which case the ternary operator resembles the Elvis operator and behaves the same.

In Python, JavaScript, Ruby, and Perl, the Elvis operator does not exist; however, the OR operator (||,or) functions similarly. In these cases, the determination between assigning the first or second operand is not entirely dependent on the first being null, but rather the first being truthy; or evaluating to a true result. What this means is that empty strings, empty arrays/lists, and undefined keys in objects/dictionaries evaluate to false and cause the second operand to be assigned.

JavaScript example:

let name = "";let user = name || "Default Name"; # Default Name

Python example:

person = {
"first_name": "Jonathan",
"last_name": "Hsu"
}
middle_initial = person['middle_name'][0] or None # None

Why Would I Use the Elvis Operator?

I’ve found the primary reason for using the Elvis operator is to safeguard against null or undefined values; hence I gravitate towards its identity as a null-safety. For me, this most often presents itself when dealing with Python command-line scripts that take in arguments.

import argparseparser = argparse.ArgumentParser(description='')
parser.add_argument('--server', dest='server', help='iFormBuilder server name (ie. app.iformbuilder.com)')
args = parser.parse_args()
server = args.server or ""

The intent is to provide default values in a concise manner in the event an argument is not supplied in the command line.

Why would I want a default value for an argument? Two reasons:

First, oftentimes subsequent functions are expecting a specific data type such as a string. Rather than pass along an undefined or null value, I can use this technique to assign an empty string.

Secondly, if I want to avoid the hindrance of entering in all arguments at the command line, or I want to simplify execution for a specific customer, I can skip the arguments (assuming I’ve made them optional) and set the customer’s specific values as the second operand.

import argparseparser = argparse.ArgumentParser(description='')
parser.add_argument('--server', dest='server', help='iFormBuilder server name (ie. app.iformbuilder.com)')
args = parser.parse_args()
server = args.server or "default.iformbuilder.com"

Conclusion

What are your favorite uses for these operators?

Better Programming

Advice for programmers.

Thanks to Zack Shapiro

Jonathan Hsu

Written by

I’m a black belt problem-solver (literally). I enjoy the taking on new challenges, building skills, and sharing what I’ve learned. 🥋

Better Programming

Advice for programmers.

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