Can we use a minus operator as a Comparison Operator ?
I couldn't find like a this situtation.
function sign(x) {
return (x > 0) - (x < 0) || x;
}
CodePudding user response:
It will not act as a comparisons operator. It will act as a math operator. To this work, JavaScript converts the boolean resulting from the x > 0 and x < 0 to zero or one, then do the subtraction.
This is a weird code, but valid.
CodePudding user response:
There are two steps to describe here.
Compute sign ( 1, 0 or -1)
Handle undefined
However, also consider undefined in this formula: any comparisons will give false, and so the above subtraction will give zero.
That's a bit dangerous, could be that you forgot to assign a value to the variable, which is a common bug when you write code.
That's why the || x was added.
|| in javascript means:
Evaluate the left side. If it's truthy, return the left side. Otherwise, return the right side.
1, and -1 are truthy, and 0 is falsy, so the full expression (x > 0) - (x < 0) || x will evaluate to x if and only if the subtraction gives zero.
If x is zero, this will still give 0 which is 0.
If x is null, this will give null which is 0.
If x is undefined, this will give undefined which is NaN.
Getting a NaN in your calculation will quickly cause all your subsequent results to be NaN, warning you that there was something undefined that you probably forgot.
Note that the x still evaluate to 0 if x is null er empty string '', so this code won't change the (mayybe unexpected) result zero for those special cases.

