简体   繁体   中英

What is the JavaScript equivalent for Swift ?? operator

In swift, x = y ?? z 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); } 

The ternary operator will achieve a similar result

x = (y ? y : z)

Strictly speaking to avoid implicit typeconversion you may want something like

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

Short circuit assignment like x = x || y x = x || y feels like a mis-use of the || operator which could lead to confusion down the road. However I think it's a matter of taste which to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM