Member-only story

Did You Know There’s an Elvis Operator?

What other clever operator names are out there?

Jonathan Hsu
Better Programming
3 min readNov 18, 2019

--

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?

Like other operators with colloquial names, Elvis has a technical or formal name as well. Falling in the class of binary assignment operators — meaning it takes two operands used for assignment — the Elvis operator is a “logical or” for the purpose of assignment to a variable (or constant).

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"

--

--

Responses (1)

Write a response