Question

It just seems so redundant and ugly. I've been using that expression quite often lately and there has to be another way.

"Assign y to x if it is valid otherwise leave x unchanged"

x = y ? y : x
Was it helpful?

Solution

You could do this, by using logical or

x = y || x;

If y is truthy, x will be equal to y after assignment.

Else x will be the same.

Here is an explanation

Look for the Other types section: mdn re-introduction to javascript

UPDATE: If you plan on using bitwise operators to do the trick, please take note that it only works with 32 bits integers to swap such values as x and y mentionned above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top