Differences between the Elvis operator: and the zero coalescer operator


Reading this question I found a reference to the call Elvis operator (link in English) or ?: that is very similar to the operator || used in javascript or also called operator of null coalescence (link in English).

Investigating more about both I could not distinguish any difference between them which led me to wonder, Is there really any difference? If there is not, 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 exists and is not null but returns bar

Null coalescent operator

var variable = foo || bar

that does exactly the same thing

Note: The elvis operator is not part of the javascript language, instead the ternary operator .

asked by devconcept 07.01.2016 в 15:38

2 answers


Both behave the same, but the difference is in which languages you are using it.

For example the Elvis Operator is not available in Javascript , since for that we have the || or double pipe.

On the other hand, PHP does not have the || to perform a null coalescent operator and therefore the ?: is used, simply a if ternario or failing the ?? .

If you look at the Wikipedia article that you place, and you look at the languages that are used the Elvis Operator only appear. C , Groovy and PHP

answered by 07.01.2016 / 15:52

If a = false ,

a ?? 'x'  ->  a
a || 'x'  ->  x

In some languages there are several false values (usually they are false , null , 0 , "" , empty list, etc.). The zero coalescence operator would return those values if they are on the left side (except with null , of course), while the operator Elvis would return those on the other side.

answered by 07.01.2016 в 15:48