Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JavaScript equivalent for Swift ?? operator

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?

like image 341
user31415 Avatar asked Dec 15 '22 05:12

user31415


1 Answers

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);
}
like image 67
gurvinder372 Avatar answered Jan 10 '23 04:01

gurvinder372