Reading this question I found a reference to the so-called Elvis operator (link in English) or ?:
which is very similar to the operator ||
used in javascript or also called the null coalescence operator (link in English).
Investigating more about both I could not distinguish any difference between them which led me to ask myself, is there really a difference? If there isn't, then why are there two references to something that semantically means the same thing?
Examples of the elvis operator
var variable = foo ?: bar
Returns foo
if foo
it exists and is not null else returnsbar
Null coalescing operator
var variable = foo || bar
which does exactly the same
Note: The elvis operator is not part of the javascript language, the ternary operator is instead .
Both behave the same, but the difference is in which languages you are using it.
For example the
Elvis Operator
is not available inJavascript
, since for that we have the||
o double pipe.On the other hand, in PHP, for example, there is no || to perform Null Coalescing Operator and for this the
?:
, simply aif ternario
or failing that the??
.If you look at the Wikipedia Article you post, and look at the languages it's used it
Elvis Operator
just shows up.C
,Groovy
andPHP
Yes
a = false
,In some languages there are several false values (usually they are
false
,null
,0
,""
, empty list, etc.). The null coalescing operator would return those values if they are on the left side (except withnull
, of course), while the Elvis operator would return those on the other side.