In swift, x = y ?? z
means that x equals y, unless y is null/nil, in which case, x equals z. What is the JavaScript equivalent?
x = y || z; //x is y unless y is null, undefined, "", '', or 0.
If you want to exclude 0
from falsey
values then,
x = ( ( y === 0 || y ) ? y : z ); //x is y unless y is null, undefined, "", '', or 0.
Or if you want to exclude false
as well from falsey
values then,
x = ((y === 0 || y === false || y) ? y : z);
DEMO
var testCases = [
[0, 2],
[false, 2],
[null, 2],
[undefined, 2],
["", 2],
['', 2],
]
for (var counter = 0; counter < testCases.length - 1; counter++) {
var y = testCases[counter][0],
z = testCases[counter][1],
x = ((y === 0 || y === false || y) ? y : z);
console.log("when y = " + y + " \t and z = " + z + " \t then x is " + x);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With