What is the JavaScript equivalent for Swift? operator

In swift, the value x = y ?? zmeans that x is y if y is not null / nil, in which case x is z. What is the equivalent of JavaScript?

+4
source share
2 answers

ternary operator will achieve a similar result

x = (y ? y : z)

Strictly speaking, to avoid implicit typeconversion , you might need something like

x = (null !== y ? y : z)

Assigning type short circuits is x = x || ylike misusing an operator ||, which can lead to confusion in the future. However, I think it is a matter of taste to be used.

+3
source
x = y || z; //x is y unless y is null, undefined, "", '', or 0.

0 falsey ,

x = ( ( y === 0 || y ) ? y : z ); //x is y unless y is null, undefined, "", '', or 0.

, false falsey,

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);
}
Hide result
+9

All Articles