Behaviour similar to that of the operator ??
of C# no
javascript, using the or logical: ||
.
There are however some differences, and for this we have to understand what the
operator ||
of javascript means.
var resultado = valorA || valorB;
is exactly the same as:
var resultado = valorA ? valorA : valorB;
It turns out that in javascript, virtually all values can treated
logical form, ie converted to true or false. As for the operation
previous, when the value valorA
is treated as true, the result of
expression is its own value. When it is treated as false, the result of
expression is the value valorB
.
We must then understand what is treated as true and as false.
What is false:
- empty string: ""
- number 0 (zero)
- false
- null
- Undefined
- Nan
What is true:
- all that is not false... including the following
- empty strings: "0", "true", "false" (it is important to remember this)
- all numbers different from 0: 1, -1, -1000, 1/10
- true
Some examples
false || "texto qualquer" // "texto qualquer"
"" || "texto qualquer" // "texto qualquer"
0 || "texto qualquer" // "texto qualquer"
null || "texto qualquer" // "texto qualquer"
undefined || "texto qualquer" // "texto qualquer"
"algum texto" || "texto qualquer" // "algum texto"
1 || "texto qualquer" // 1
Noted the difference to the ??
of C#... only if the first is null
is that the
second will be the result, otherwise the result is the first.
Different from javascript where the second is the result, if the value of the first
for falso
, 0
or ""
.